Search code examples
rggplot2plotlyr-plotly

Dropdown menu in R plotly to plot subsample


I am trying to use a dropdown menu to plot a subsample of a dataset using the dropdown menu from plotly in R.

This is what I have so far (based on this answer) without sucess:

library(data.table)
library(ggplot2)
library(plotly)

X <- data.table(xcoord = 1:10, ycoord = 1:10)
Z <- X[xcoord < 5]

gg <- ggplot(X, aes(x = xcoord, y = ycoord)) + geom_point()

ggplotly(gg) %>%
  layout(updatemenus = list(
    list(buttons = list(
      list(method = "restyle",
           args = list(list("x", list(X$xcoord)),
                       list("y", list(X$xcoord))),
           label = "X"),
      list(method = "restyle",
           args = list(list("x", list(Z$xcoord)),
                       list("y", list(Z$ycoord))),
           label = "Z")
    ))
  ))


Solution

  • Found the solution: had to use named lists instead.

    ggplotly(gg) %>%
      layout(updatemenus = list(
        list(buttons = list(
          list(method = "restyle",
               args = list(list(x = list(X$xcoord)),
                           list(y = list(X$xcoord))),
               label = "X"),
          list(method = "restyle",
               args = list(list(x = list(Z$xcoord)),
                           list(y = list(Z$ycoord))),
               label = "Z")
        ))
      ))