简体   繁体   中英

Convert alpha aesthetics with ggplotly

I have been working on heatmaps using in ggplot2 , and I am now trying to convert them to ggplotly to build a shiny app with them. Everything works (more or less) fine except for the translation of the alpha aesthetic in geom_tile (same issue if I use geom_raster ). After a full day of googling and reading related answers, I have not found any solution yet.

I have tried with different data and specifications, and so far no luck at all. The problem seems to be specific to heatmaps, as alpha translates well if I use geom_point. Problem is, I really need heatmaps for what I'm doing.

I have produced a reproducible example that shows the issue.

library(ggplot2)
library(plotly)
library(dplyr)

sample<- data.frame(a = 1:10,
                b = 11:20,
                c = 31:40,
                d = rep(c("a", "b"), 5))


plot <- sample%>%
  ggplot(aes(x=a, y=b, fill = c, alpha = d))+
  geom_raster()

plot

ggplotly(plot)

You'll see the output is quite different. Any ideas or has anyone had a similar issue?

ggplot:

ggplot

ggplotly:

ggplotly

I agree there's something not being translated as intended by plotly::ggplotly() . I tried a few variations of ggplot2::geom_rect() & ggplot2::geom_tile() and ggplot2::scale_color_manual() & ggplot2::scale_color_identity() .

Here's a heatmap example written straight to plotly, without the ggplot2 layer. I'm not seeing a directly way to map alpha/opacity.

This should meet your needs if you didn't need to vary the alpha in plotly, and simply needed the geom dimensions to be correct.

ds <- tibble::tibble(
  x   =  1:10,
  y   = 11:20,
  z   = 31:40,
  a1  = rep(c("a", "b"), 5),
  a2  = rep(c( .1,   .4), 5)
)

plot_ly(ds) %>% 
  add_heatmap(x = ~x, y = ~y, z = ~z, opacity = .5,  colors = "YlGnBu")

绘图热图

If you need to vary alpha, I'm guessing the best current approach is to create a custom palette that sets all four channels of rgb a .

In case anyone runs into a similar issue, I found a way around this (as it seems to be a bug of ggplotly) by creating the heatmap with geom_point() and adjusting the shape and size of the points until it looked the same. Apparently, ggplotly does translate well the alpha aes from this geom.

This is the final result (the aim of the shiny app is to be able to select these diagonals with a reference-year to isolate them from the others):

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM