You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 21:36:02