0

I have a dataset with the same structure as the Iris one but with 50+ variables. Therefore, I'd like to create a loop in order to automatically create the menu. Thanks!

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 Answer 1

1

The function iterates through the number of menu items and creates a button for each in the format plotly requires.

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))
    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.