plotly / plotly.R

An interactive graphing library for R
https://plotly-r.com
Other
2.54k stars 622 forks source link

Mapping alpha to continuous variable in geom_tile()/geom_raster() #1579

Open aaumaitre opened 5 years ago

aaumaitre commented 5 years ago

I am trying to convert a heatmap I created with ggplot to a plotly object. Everything works fine, except no matter what I do, it won't translate the alpha values (I have tried both having it as aes- what I want- but also giving it a random value and it won't work. This is the ggplot code and output, which works fine:

I have tried both geom tile and geom raster and none of them seem to work.

 plot <- datos%>%
    ggplot(aes(Var2, Var1, fill = value,  alpha = dum,
text = paste("<b>Edad:</b>", Var2, "<br>",
                                                    "<b>Año:</b>", Var1, "<br>",
                                                    "<b> Año de nacimiento: </b>", (Var1 - Var2), "<br>",
                                                    "<b>Renta relativa:</b>", format(value, 
                                                                              big.mark = ".", 
                                                                              scientific = FALSE, 
                                                                              digits = 2))))+
  geom_raster()+
  scale_alpha(range = c(0.6, 1))+
  scale_x_continuous(breaks = seq(20, 75, by = 5), limits = c(20, 80))+
  scale_y_continuous(breaks = seq(2008, 2016, by = 2 ), limits = c(2008, 2016))+
  theme_minimal()

ggplot output (with a little more formatting: image

ggplotly output (just doing ggplotly(plot)): image

cpsievert commented 5 years ago

A minimal example:

library(plotly)
df <- data.frame(
    x = rep(c(2, 5, 7, 9, 12), 2),
    y = rep(c(1, 2), each = 5),
    z = factor(rep(1:5, each = 2)),
    w = rep(diff(c(0, 4, 6, 8, 10, 14)), 2)
)
ggplot(df, aes(x, y)) +
    geom_tile(aes(fill = w, alpha = w), colour = "grey50")
ggplotly()
aaumaitre commented 5 years ago

In case anyone runs into a similar issue, I worked out a way around by using geom_point to create the heatmap. With the appropriate point size and shape it ended up looking quite similar, and the alpha was translated properly. In case you want to see the result:

image