首页 > 解决方案 > 在R闪亮中绘制填充颜色透明度

问题描述

在 R 和情节。我如何尝试使用 alpha 来控制分组散点图的透明度。我按照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)

但填充颜色是透明的,alpha似乎没有做任何事情。 在此处输入图像描述

Plotly 的 fillcolor中给出的解决方案默认为半透明,想要不透明的作品:

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)

作品:

在此处输入图像描述

但是,在 Shiny 中,这会给出以下警告并且不透明度会丢失

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

有没有办法来解决这个问题?

注意:第二个图是windows中的一个片段,因为当点击下载png plotly按钮时,第二个图仍然将图下载为透明的。这两个问题可能是相关的。

标签: rshinyplotly

解决方案


我在这里查看https://plotly.com/python/filled-area-plots/并使用了fill='tonexty'. 现在alpha = 1开始工作并控制填充的透明度。

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

给出:

在此处输入图像描述

我仍然认为这是 API 的疏忽。当stackgroup = 'one', groupnorm = 'percent'填充是自动的fill='tonexty'。不需要添加它来控制不透明度。此外,alpha = 1仅仅因为添加了作品而变得活跃fill='tonexty'是令人困惑的。


推荐阅读