R Plotly色带消失与按钮

时间:2019-11-06 01:18:10

标签: r plotly

下面我有一个玩具示例,其中有一个散点图保持在相同的x和y坐标上,但我想通过不同列中的值为散点着色。当我单击“ Petal.Width”时,出现正确的散点颜色,但颜色栏消失。理想情况下,我希望颜色条的标题与单击的按钮相同,并且颜色条的比例随每个单击的按钮而变化。

updatemenus <- list(
  list(
    active = -1,
    type= 'buttons',
    buttons = list(
      list(
        label = "Petal.Length",
        method = "update",

        args = list(list(visible = c(FALSE, TRUE)))),
      list(
        label = "Petal.Width",
        method = "update",
        args = list(list(visible = c(TRUE, FALSE))))
    )
  )
)

iris %>%
  plot_ly(type = "scatter",
          mode = 'markers') %>% 
  add_trace(x = ~Sepal.Length, 
          y = ~Sepal.Width,
          color = ~Petal.Length,
          visible = TRUE,
          name = "Petal.Length") %>% 
  add_trace(x = ~Sepal.Length, 
          y = ~Sepal.Width,
          color = ~Petal.Width,
          visible = FALSE,
          name = "Petal.Width") %>% 
  layout(updatemenus=updatemenus) 

这是我运行代码时显示情节的方式

original

在这里,当我单击“ Petal.Width”

original

2 个答案:

答案 0 :(得分:2)

如果将来有人发现此问题,我会回答:

对我有用的是在两个跟踪(colorbar)中为add_trace指定一些参数。

您将以这样的结尾:

iris %>%
  plot_ly(type = "scatter",
          mode = 'markers') %>% 
  add_trace(x = ~Sepal.Length, 
          y = ~Sepal.Width,
          color = ~Petal.Length,
          visible = TRUE,
          name = "Petal.Length",
          colorbar= list(thicknes=20,
                         len = 0.35,
                         x=0.05,
                         y=0.35)
            ) %>% 
  add_trace(x = ~Sepal.Length, 
          y = ~Sepal.Width,
          color = ~Petal.Width,
          visible = FALSE,
          name = "Petal.Width",
          colorbar= list(thicknes=20,
                         len = 0.35,
                         x=0.05,
                         y=0.35)
            ) %>% 
  layout(updatemenus=updatemenus) 

您可以使用Plotly documentation for R

中的参数来进一步自定义颜色栏。

答案 1 :(得分:0)

将您的 color 参数移至 marker 的参数列表

iris %>%
  plot_ly() %>%
  add_trace(
    type = "scatter",
    mode = "markers",
    x = ~Sepal.Length,
    y = ~Sepal.Width,
    visible = TRUE,
    name = "Petal.Length",
    showlegend = F,
    marker = list(
      color = iris[["Petal.Length"]],
      showscale = T,
      colorbar = list(title = "aaaaaaaaaaaaa")
    )
  ) %>%
  add_trace(
    type = "scatter",
    mode = "markers",
    x = ~Sepal.Length,
    y = ~Sepal.Width,
    visible = FALSE,
    name = "Petal.Width",
    showlegend = F,
    marker = list(
      color = iris[["Petal.Width"]],
      showscale = T,
      colorbar = list(title = "bbbbbbbbb")
    )
  ) %>%
  layout(updatemenus = updatemenus)