New feature: Dropdown menus in Plotly and R

[This article was first published on R – Modern Data, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 %
  add_lines(y = ~y1, name = "A") %>%
  add_lines(y = ~y2, name = "B", visible = F)


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

Changing chart type

library(MASS)
library(plotly)
covmat %
  add_markers(marker = list(opacity = 0.3, line = list(color = "black", width = 1)))

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

To leave a comment for the author, please follow the link and comment on their blog: R – Modern Data.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)