【问题标题】:Loop | Plotly menu循环 |剧情菜单
【发布时间】:2019-03-09 07:48:48
【问题描述】:

我有一个数据集,其结构与 Iris 相同,但包含 50 多个变量。因此,我想创建一个循环以自动创建菜单。谢谢!

library(plotly)
p <- iris %>%
plot_ly(
type = 'scatter', 
x = ~Sepal.Length, 
y = ~Petal.Length,
text = ~Species,
hoverinfo = 'text',
mode = 'markers', 
transforms = list(
list(
type = 'filter',
target = ~Species,
operation = '=',
value = unique(iris$Species)[1]
)
)) %>% layout(
updatemenus = list(
list(
type = 'dropdown',
active = 0,
buttons = list(
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[1]),
label = unique(iris$Species)[1]),
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[2]),
label = unique(iris$Species)[2]),
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[3]),
label = unique(iris$Species)[3])
)
)
)
)
p

【问题讨论】:

    标签: r for-loop dplyr r-plotly


    【解决方案1】:

    该函数遍历菜单项的数量,并以 plotly 所需的格式为每个菜单项创建一个按钮。

    library(plotly)
    
    get_menu_list <- function(names){
      n_names = length(names)
      buttons = vector("list",n_names)
    
      for(i in seq_along(buttons)){
        buttons[i] = list(list(method = "restyle",
                          args = list("transforms[0].value", names[i]),
                          label = names[i]))
      }
    
      return_list = list(
        list(
          type = 'dropdown',
          active = 0,
          buttons = buttons
        )
        )
    
        return(return_list)
    }
    
    p <- iris %>%
      plot_ly(
        type = 'scatter', 
        x = ~Sepal.Length, 
        y = ~Petal.Length,
        text = ~Species,
        hoverinfo = 'text',
        mode = 'markers', 
        transforms = list(
          list(
            type = 'filter',
            target = ~Species,
            operation = '=',
            value = unique(iris$Species)[1]
          )
        )) %>% layout(
          updatemenus = get_menu_list(unique(iris$Species))
        )
    

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多