简体   繁体   中英

plotly fill color transparency in R shiny

In R and plotly. How can I tried to use alpha to control the transparency of a grouped scatter plot. I followed the example in Plotly's fillcolor defaults to half-transparency, want no-transparency :

df <- data.frame(x = rep(LETTERS[1:5], 3), 
                 y = rexp(15, rate = 0.5),
                 z = c(rep("Adam", 5), rep("Arthur", 5), rep("Ford", 5)))
df <- arrange(df, desc(z))
plot_ly(df, x = ~x, y = ~y, color = ~z, type = 'scatter', stackgroup = 'one',
        groupnorm = 'percent', colors =  gg_color(Nv), alpha = 1, alpha_stroke = 1)

But the fill colours are transparent and alpha does not seem to do anything. 在此处输入图像描述

The solution given in Plotly's fillcolor defaults to half-transparency, want no-transparency works:

library(htmlwidgets)
library(htmltools)
fillOpacity = function(., alpha = 0.5) {
  css = sprintf("<style> .js-fill { fill-opacity: %s !important; } </style>", alpha)
  prependContent(., HTML(css))
}
plot_ly(df, x = ~x, y = ~y, color = ~z, type = 'scatter', stackgroup = 'one',
        groupnorm = 'percent', colors =  gg_color(Nv), alpha = 1, alpha_stroke = 1) %>%
fillOpacity(alpha = 1)

Works:

在此处输入图像描述

However, in Shiny this gives the following warning and the opacity is lost

Warning in renderWidget(instance) :
  Ignoring prepended content; prependContent can't be used in a Shiny render call

Is there a way to fix this?

Note: The second figure is a snip in windows, because when clicking on the download png plotly button, the second graph still downloads the graph as transparent. The two issues are probably related.

I looked here https://plotly.com/python/filled-area-plots/ and used fill='tonexty' . Now the alpha = 1 works and controls the transparency of the fill.

ply = plot_ly(df, x = ~x, y = ~y, color = ~z, type = 'scatter', stackgroup = 'one',
        groupnorm = 'percent', alpha = 1, alpha_stroke = 1, mode = 'marker', opacity=1, fill='tonexty');ply

gives:

在此处输入图像描述

I still think this is an oversight in the API. when stackgroup = 'one', groupnorm = 'percent' the fill is automatically fill='tonexty' . there shouldn't be a need to add it in order to manipulate the opacity. Also, alpha = 1 becoming active only because works fill='tonexty' has been added is confusing.

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