【问题标题】:Plotly drop down menu not restyling 'y' correctly绘图下拉菜单未正确重新设置“y”
【发布时间】:2017-06-24 05:20:44
【问题描述】:

这是示例数据的代码:

library(tidyverse)
library(plotly)

df <- data_frame(
  date = Sys.Date() - seq(0, 99, by = 0.2)[2:101],
  cut = rep(c("Ideal", "Premium", "Very Good", "Good", "Fair"), 20),
  y = sample_n(diamonds, size = 100)$depth,
  z = sample_n(diamonds, size = 100)$price
)

这是情节的代码:

plot_ly(df, x = ~date, y = ~y, color = ~cut, 
        type = "scatter", mode = "lines") %>%
layout(
  title = "Drop down menus - Change y",
  xaxis = list(title = "x"),
  yaxis = list(title = "y"),
  updatemenus = list(
    list(
      y = 0.7,
      buttons = list(
        list(method = "restyle",
             args = list("y", list(~y)),
             label = "Show Y"),
        list(method = "restyle",
             args = list("y", list(~z)),
             label = "Show Z")))
))

发生的事情是我执行了代码,绘制了绘图,并且它看起来像我想要的那样:随着时间的推移分类变量的事物计数。目标是让下拉菜单将一个 y 变量替换为另一个变量,在本例中为 z

根据文档中的一些玩具示例和这里的一些答案,我觉得这应该可行。相反,看起来所有值都奇怪地折叠成一行。似乎没有办法在不重新运行代码的情况下将绘图恢复到原始状态。

有人知道如何让它正常工作吗?

这是我的plotly 版本:

packageVersion("plotly")
[1] ‘4.5.6.9000’

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    你可以让它工作

    • 首先创建一个“空”图:plot_ly(df, x = ~date, color = ~cut)
    • add_trace 对于每个 y 值:add_trace(y = ~z, type = 'scatter', mode = 'lines', visible=F) 但隐藏第二条轨迹
    • 应用restyle 隐藏/显示每组:args = list("visible", append(rep(list(TRUE), 5), rep(list(FALSE), 5)))

    在 Ubuntu 16 和 Windows 10 上的 R-Studio 上使用 plotly 4.5.6 确实为我工作。

    library('tidyverse')
    library('plotly')
    
    df <- data_frame(
      date = Sys.Date() - seq(0, 99, by = 0.2)[2:101],
      cut = rep(c("Ideal", "Premium", "Very Good", "Good", "Fair"), 20),
      y = sample_n(diamonds, size = 100)$depth,
      z = sample_n(diamonds, size = 100)$price
    )
    p <- plot_ly(df, x = ~date, color = ~cut) %>%
    add_trace(y = ~y, type = 'scatter', mode = 'lines', visible=T) %>%
    add_trace(y = ~z, type = 'scatter', mode = 'lines', visible=F)
    
    p <- p %>% layout(
      updatemenus = list(
        list(
          buttons = list(
            list(method = "restyle",
                 args = list("visible", append(rep(list(TRUE), 5), rep(list(FALSE), 5))),
                 label = "Show Y"),
            list(method = "restyle",
                 args = list("visible", append(rep(list(FALSE), 5), rep(list(TRUE), 5))),
                 label = "Show Z")))
    ))
    

    【讨论】:

    • 感谢@Maximilian-Peters 提供有用的解决方案!我也尝试过这样做,但我没有使用add_trace(),我使用了add_lines()。不过这可能无关紧要——看起来append(rep(list(T), 5), rep(list(F), 5)) 发生了魔法——这是如何工作的?为什么args 变量需要该值 5 次?是因为cut 有五个唯一的分类值吗?再次感谢!
    • @RobertMitchell:也打败了我。在add_trace 中,给出visible 参数一次就足够了,但之后需要重复。可能是因为cut,跟踪随后被拆分并从add_trace 调用继承visible 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    相关资源
    最近更新 更多