4

I'm designing a shiny app with plotly graphs and ran into an issue when trying to set up a reactive value for the alpha (transparency of the bars in a bar plot).

Essentially, plotly doesn't like the alpha argument, but I can't figure out why. Seems to think I'm supplying less than 10 values, which I'm not... I've created a reproducible example showing that the alpha argument works in ggplot but not in plotly:

library(data.table)
library(ggplot2)
library(plotly)
library(scales)

# Create reproducible example -------------------------------------------------

df <- data.table(fiscal=2013:2022,value=runif(10,min=100,max=200))

# Create vector of alpha values for the ggplot --------------------------------
alpha_values <- data.table(x=2013:2022,y=rep(0.5,10))
alpha_values[x %in% 2013:2015]$y <- 1
alpha_values[x==2022,y:=1]
# (2015 to 2021 will the 50% transparent)

g1 <- ggplot(df,aes(fiscal,value))+
  geom_bar(stat="identity",fill='#3D78A5',alpha=alpha_values$y)+
  scale_x_continuous(breaks=unique(df$fiscal))+
  scale_y_continuous(labels=comma)+
  labs(title="",x="Fiscal Year",
       y= "Random, number")

# Works fine using ggplot call ------------------------------------------------
g1

# Alpha argument does not work in ggplotly ------------------------------------
ggplotly(g1)

# (Error: alpha must be of length 1 or the same length as x)

It is possible to use the alpha argument in combination with ggplot/plotly?

ben.watson.ca
  • 181
  • 1
  • 2
  • 8

2 Answers2

3

This is likely due to how plotly.js handles a set of discrete values for alpha. A work around is to make the alpha value a factor, as each bar is essentially plotted as a separate trace. I have also put alpha into aes.

g1 <- ggplot(df,aes(fiscal,value))+
  geom_bar(stat="identity",fill='#3D78A5',aes(alpha=factor(alpha_values$y)))+
  scale_x_continuous(breaks=unique(df$fiscal))+
  scale_y_continuous(labels=comma)+
  labs(title="",x="Fiscal Year",
       y= "Random, number")

You can also see: Using alpha and manual colours with ggplotly

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
3

Per Andy's answer, making the alpha values a factor allowed plotly to render the ggplot object, however the alpha transparencies were off from my initial values and the new factor added a legend to the plot. To correct this you can add the following lines:

scale_alpha_manual(values=c(0.5,1))+
  theme(legend.position = "none")+

(with the values being whatever alpha values you want to assign to your newly created alpha factor).

Solution looks like this:

g1 <- ggplot(df,aes(fiscal,value))+
  geom_bar(stat="identity",fill='#3D78A5',aes(alpha=factor(alpha_values$y)))+
  scale_x_continuous(breaks=unique(df$fiscal))+
  scale_y_continuous(labels=comma)+
  scale_alpha_manual(values=c(0.5,1))+
  theme(legend.position = "none")+
  labs(title="",x="Fiscal Year",
       y= "Random, number")

ggplotly(g1)
ben.watson.ca
  • 181
  • 1
  • 2
  • 8