Петля |Плотно меню - PullRequest
       6

Петля |Плотно меню

0 голосов
/ 09 марта 2019

У меня есть набор данных с такой же структурой, как у 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

1 Ответ

0 голосов
/ 09 марта 2019

Функция перебирает количество пунктов меню и создает кнопку для каждого в формате, необходимом для графика.

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))
    )
...