如何设置Plotly散点图图例点的不透明度与图内绘制点不同
可以实现,有两种常用解决方案:
方案1:将透明度设置移到marker参数中(最简洁)
add_trace顶层的opacity参数会同时作用于图中标记和对应图例项,把透明度配置放到marker参数内仅作用于图内点,图例标记默认保持完全不透明。
library(dplyr) library(plotly) set.seed(77) sample_data = data.frame(x = c(1:100), y = rnorm(100, mean = 1, sd = 0.5)) %>% mutate(z = x*y, attr = if_else(x>50,"Big","Small")) plot_ly() %>% add_trace(x = sample_data$x, y = sample_data$y, z = sample_data$z, color = sample_data$attr, colors = c("cyan4","orange"), type = "scatter3d", mode = "markers", # 移除顶层opacity,移到marker内设置 marker = list(opacity = 0.5, size = 1) ) %>% layout(legend = list(x = 0.5, y = 0.9, bgcolor = "rgba(0,0,0,0)"))
方案2:强制指定图例项样式透明度
如果需要保留顶层opacity配置,可在layout的legend参数中添加itemstyle配置,强制图例标记不透明:
library(dplyr) library(plotly) set.seed(77) sample_data = data.frame(x = c(1:100), y = rnorm(100, mean = 1, sd = 0.5)) %>% mutate(z = x*y, attr = if_else(x>50,"Big","Small")) plot_ly() %>% add_trace(x = sample_data$x, y = sample_data$y, z = sample_data$z, color = sample_data$attr, colors = c("cyan4","orange"), type = "scatter3d", mode = "markers", opacity = 0.5, size = 1) %>% layout(legend = list(x = 0.5, y = 0.9, bgcolor = "rgba(0,0,0,0)", # 新增itemstyle配置强制图例标记不透明 itemstyle = list(opacity = 1)))
两种方案都可以实现图中点50%透明、图例标记100%不透明的效果。
内容的提问来源于stack exchange,提问作者Cem
相关产品推荐
相关产品推荐

