Andyy Hu
Andyy Hu

Reputation: 59

Customizing Layout in Drop down menu in Plotly R

I was looking in the documentation to create drop-down menus in plot_ly using R and found this code chunk, and was curious how I would add unique titles for each of the three graphs

plot_ly(mtcars, x = ~gear) %>%
  add_trace(y = ~cyl, name = "cyl", visible = F, color=I("blue")) %>%
  add_trace(y = ~hp, name = "hp", visible = F, color=I("green")) %>%
  add_trace(y = ~gear, name = "gears", visible = F, color=I("red")) %>%
  layout(
    yaxis = list(title = "y"),
    updatemenus = list(
      list(
        y = 0.7,
        buttons = list(
          list(method = "restyle",
               args = list("visible", list(TRUE, FALSE, FALSE)),
               label = "cyl"),
          list(method = "restyle",
               args = list("visible", list(FALSE, TRUE, FALSE)),
               label = "hp"),
          list(method = "restyle",
               args = list("visible", list(FALSE, FALSE, TRUE)),
               label = "gear")))
    )
  )

Citation: Generating Dropdown menu for Plotly charts

Upvotes: 0

Views: 393

Answers (1)

Quinten
Quinten

Reputation: 41337

If I understand you correctly, you can change the label of each button to a title whatever you want like this:

library(plotly)
plot_ly(mtcars, x = ~gear) %>%
  add_trace(y = ~cyl, name = "cyl", visible = F, color=I("blue")) %>%
  add_trace(y = ~hp, name = "hp", visible = F, color=I("green")) %>%
  add_trace(y = ~gear, name = "gears", visible = F, color=I("red")) %>%
  layout(
    yaxis = list(title = "y"),
    updatemenus = list(
      list(
        y = 0.7,
        buttons = list(
          list(method = "restyle",
               args = list("visible", list(TRUE, FALSE, FALSE)),
               label = "title1"),
          list(method = "restyle",
               args = list("visible", list(FALSE, TRUE, FALSE)),
               label = "title2"),
          list(method = "restyle",
               args = list("visible", list(FALSE, FALSE, TRUE)),
               label = "title3")))
    )
  )

Created on 2022-07-06 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions