简体   繁体   English

R Plotly 颜色条随按钮消失

[英]R Plotly Colorbar Disappears with Buttons

I have a toy example below where I have a scatterplot that stays on the same x and y coordinates but I'd like to color the scatter points by the values in different columns.我在下面有一个玩具示例,其中我有一个散点图,它保持在相同的 x 和 y 坐标上,但我想通过不同列中的值对散点进行着色。 When I click on "Petal.Width" the correct scatter point colors appear but the colorbar disappears.当我单击“Petal.Width”时,会出现正确的散点 colors,但颜色条会消失。 Ideally I'd like the title of the color bar to be the same as the clicked button and the scale of the color bar to change with each clicked button.理想情况下,我希望颜色条的标题与单击的按钮相同,并且颜色条的比例随着每个单击的按钮而改变。

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) 

Here is how the plot is displayed when i run my code这是我运行代码时 plot 的显示方式

原来的

Here it is when I click "Petal.Width"这是当我单击“Petal.Width”时

原来的

I will answer in case someone finds this issue in the future:如果将来有人发现这个问题,我会回答:

What worked for me is specifying some arguments for colorbar in both traces ( add_trace ).对我有用的是在两条轨迹( colorbar )中为颜色条指定一些add_trace

You would end with something like this:你会以这样的方式结束:

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) 

You can further customize your colorbar with the arguments found in the Plotly documentation for R您可以使用 R 的Plotly 文档中的 arguments 进一步自定义颜色条

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM