【问题标题】:Plotly marker legend appears multiple times on plot情节标记图例在情节上多次出现
【发布时间】:2021-12-26 20:02:19
【问题描述】:

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

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")
              )

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    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 由条形和标记共享,但颜色在每个跟踪中单独定义。因此,您可以获得条形图的单个图例和标记的单个图例。

    剧情

    【讨论】:

      猜你喜欢
      • 2019-07-14
      • 2019-03-31
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2018-03-30
      • 1970-01-01
      相关资源
      最近更新 更多