In this post we’ll showcase the new dropdown menu button feature. It adds a layer of interactivity that is similar to shiny but supported within the plotly package.
Adding new menu buttons is as simple as specifying the updatemenus parameter inside layout.
Each dropdown menu needs to be a separate list with position parameters x and y a well as a buttons parameter which houses individual named items with some additional parameters. Below are some examples:
Re-Styling a graph
library(plotly) x <- seq(-2*pi, 2*pi, length.out = 1000) df <- data.frame(x, y1 = sin(x), y2 = cos(x)) p <- plot_ly(df, x = ~x) %>% add_lines(y = ~y1, name = "A") %>% add_lines(y = ~y2, name = "B", visible = F) p <- p %>% layout( title = "Drop down menus - Styling", xaxis = list(domain = c(0.1, 1)), yaxis = list(title = "y"), updatemenus = list( list( y = 0.8, buttons = list( list(method = "restyle", args = list("line.color", "blue"), label = "Blue"), list(method = "restyle", args = list("line.color", "red"), label = "Red"))), list( y = 0.7, buttons = list( list(method = "restyle", args = list("visible", list(TRUE, FALSE)), label = "Sin"), list(method = "restyle", args = list("visible", list(FALSE, TRUE)), label = "Cos"))) )) p
Changing chart type
library(MASS) library(plotly) covmat <- matrix(c(0.8, 0.4, 0.3, 0.8), nrow = 2, byrow = T) df <- mvrnorm(n = 10000, c(0,0), Sigma = covmat) df <- as.data.frame(df) colnames(df) <- c("x", "y") p <- plot_ly(df, x = ~x, y = ~y) %>% add_markers(marker = list(opacity = 0.3, line = list(color = "black", width = 1))) p <- p %>% layout( title = "Drop down menus - Plot type", xaxis = list(domain = c(0.1, 1)), yaxis = list(title = "y"), updatemenus = list( list( y = 0.8, buttons = list( list(method = "restyle", args = list("type", "scatter"), label = "Scatter"), list(method = "restyle", args = list("type", "histogram2d"), label = "2D Histogram"))) )) p