Plotly 标记图例在图上多次出现

Plotly marker legend appears multiple times on plot

我有一个条形图,其中条形根据因子变量着色。我需要在指定位置的每个栏上放置一个目标标记。我可以毫无问题地将标记放在图上,但在图例中,目标标记出现了三次,而我只希望它出现一次。我相信这种行为与条形图的颜色有关,但这种颜色是必须保留的。谁能给我一个解决方案,让目标标记只在图例上出现一次?

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",
              x = 17,
              marker = list(
                color = "black")
              )

plot_ly 中的参数将为所有跟踪设置,只要没有被覆盖。在您的情况下,plot_ly 函数内的 color = ~grp 将按 grp.

对每个跟踪进行分组

一个简单的选择是在自己的轨迹中定义带有颜色的条。

代码

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

在此代码中,x 和 y 由条形和标记共享,但颜色在每条轨迹中单独定义。因此,您会得到单独的条形图例和单个标记图例。

情节