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

Plotly条形图添加marker后图例重复,如何仅保留单个marker图例

问题原因

顶层plot_ly()中配置的color = ~grp分组映射会被后续图层默认继承,add_markers()会按grp的3个因子水平拆分出3组独立标记,每组都生成一个图例条目,最终出现重复。

解决方案

在add_markers()中添加inherit = FALSE关闭父级映射继承,同时手动指定标记的y轴映射即可,原有条形的着色逻辑完全不受影响。

修改后代码如下:

library(tidyverse)
library(plotly)

data.frame(grp = c("x", "y", "z") %>% as.factor,
           vals = c(10, 15, 20)) %>% 
  plot_ly(
    x = ~vals,
    y = ~grp,
    color = ~grp,
    colors = c("red", "green", "blue"),
    type = "bar"
  ) %>% 
  add_markers(name = "target",
              inherit = FALSE,
              x = 17,
              y = ~grp,
              marker = list(color = "black")
              )

修改后图例仅会保留1个target标记条目,3个条形上的黑色标记也会正常渲染。

内容的提问来源于stack exchange,提问作者DJC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:06:01