循环| Plotly菜单

问题描述 投票:0回答:1

我有一个数据集,其结构与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个回答
0
投票

该函数遍历菜单项的数量,并按照图形要求为每个菜单项创建一个按钮。

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))
    )
© www.soinside.com 2019 - 2024. All rights reserved.