Show Sidebar Hide Sidebar

Buttons in R

How to add buttons in R with Plotly.

New to Plotly?

Plotly's R library is free and open source!
Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Version 4 of Plotly's R package is now available!
Check out this post for more information on breaking changes and new features available in this version.

library(plotly)
packageVersion('plotly')
## [1] '4.5.6.9000'

Methods

The updatemenu method determines which plotly.js function will be used to modify the chart. There are 4 possible methods:

  • "restyle": modify data or data attributes
  • "relayout": modify layout attributes
  • "update": modify data and layout attributes
  • "animate": start or pause an animation (only available offline)

Restyle Buttons

The "restyle" method should be used when modifying the data and data attributes of the graph
Update One Data Attribute This example demostrates how to update a single data attribute: line color with the "restyle" method.

library(plotly)

x <- seq(-2*pi, 2*pi, length.out = 1000)
df <- data.frame(x, y1 = sin(x))

p <- plot_ly(df, x = ~x) %>%
  add_lines(y = ~y1)


p <- p %>% layout(
  title = "Button Restyle",
  xaxis = list(domain = c(0.1, 1)),
  yaxis = list(title = "y"),
  updatemenus = list(
    list(
      type = "buttons",
      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")))
  ))

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="buttons/basic")
chart_link

Update Several Data Attributes This example demostrates how to update several data attributes: colorscale, chart type, and colorscale with the "restyle" method.

library(plotly)

p <- plot_ly(z = ~volcano, type = "heatmap", colorscale='Rainbow')

# chart option buttons
chart_types <- list(
  type = "buttons",
  direction = "right",
  xanchor = 'center',
  yanchor = "top",
  pad = list('r'= 0, 't'= 10, 'b' = 10),
  x = 0.5,
  y = 1.27,
  buttons = list(

    list(method = "restyle",
         args = list("type", "heatmap"),
         label = "Heatmap"),

    list(method = "restyle",
         args = list("type", "contour"),
         label = "Contour"),

    list(method = "restyle",
         args = list("type", "surface"),
         label = "Surface")
  ))

# color option buttons  
color_types <- list(
  type = "buttons",
  direction = "right",
  xanchor = 'center',
  yanchor = "top",
  pad = list('r'= 0, 't'= 10, 'b' = 10),
  x = 0.5,
  y = 1.17,
  buttons = list(

    list(method = "restyle",
         args = list("colorscale", "Rainbow"),
         label = "Rainbow"),

    list(method = "restyle",
         args = list("colorscale", "Jet"),
         label = "Jet"),

    list(method = "restyle",
         args = list("colorscale", "Earth"),
         label = "Earth"),

    list(method = "restyle",
         args = list("colorscale", "Electric"),
         label = "Electric")
  ))

annot <- list(list(text = "Chart<br>Type", x=0.2, y=1.25, xref='paper', yref='paper', showarrow=FALSE),
              list(text = "Color<br>Type", x=0.2, y=1.15, xref='paper', yref='paper', showarrow=FALSE))

# plot
p <- p %>% layout(
  xaxis = list(domain = c(0.1, 1)),
  yaxis = list(title = "y"),
  updatemenus = list(chart_types,color_types),
  annotations = annot)

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="buttons/charts")
chart_link

Relayout Button

The "relayout" method should be used when modiying the layout attributes of the graph.
Update One Layout Attribute This example demostrated how to update a layout attribute: shapes with the '"relayout"' method.

library(plotly)

x0 <- rnorm(400, mean=2, sd=0.4)
y0 <- rnorm(400, mean=2, sd=0.4)
x1 <- rnorm(400, mean=3, sd=0.6)
y1 <- rnorm(400, mean=6, sd=0.4)
x2 <- rnorm(400, mean=4, sd=0.2)
y2 <- rnorm(400, mean=4, sd=0.4)

# shapes components
cluster0 = list(
  type = 'circle',
  xref ='x', yref='y',
  x0=min(x0), y0=min(y0),
  x1=max(x0), y1=max(y0),
  opacity=0.25,
  line = list(color="#835AF1"),
  fillcolor="#835AF1")

cluster1 = list(
  type = 'circle',
  xref ='x', yref='y',
  x0=min(x1), y0=min(y1),
  x1=max(x1), y1=max(y1),
  opacity=0.25,
  line = list(color="#7FA6EE"),
  fillcolor="#7FA6EE")

cluster2 = list(
  type = 'circle',
  xref ='x', yref='y',
  x0=min(x2), y0=min(y2),
  x1=max(x2), y1=max(y2),
  opacity=0.25,
  line = list(color="#B8F7D4"),
  fillcolor="#B8F7D4")

# updatemenus component
updatemenus <- list(
  list(
    active = -1,
    type = 'buttons',
    buttons = list(

      list(
        label = "None",
        method = "relayout",
        args = list(list(shapes = c()))),

      list(
        label = "Cluster 0",
        method = "relayout",
        args = list(list(shapes = list(cluster0, c(), c())))),

      list(
        label = "Cluster 1",
        method = "relayout",
        args = list(list(shapes = list(c(), cluster1, c())))),

      list(
        label = "Cluster 2",
        method = "relayout",
        args = list(list(shapes = list(c(), c(), cluster2)))),

      list(
        label = "All",
        method = "relayout",
        args = list(list(shapes = list(cluster0,cluster1,cluster2))))
    )
  )
)

p <- plot_ly(type = 'scatter', mode='markers') %>%
  add_trace(x=x0, y=y0, mode='markers', marker=list(color='#835AF1')) %>%
  add_trace(x=x1, y=y1, mode='markers', marker=list(color='#7FA6EE')) %>%
  add_trace(x=x2, y=y2, mode='markers', marker=list(color='#B8F7D4')) %>%
  layout(title = "Highlight Clusters", showlegend = FALSE,
         updatemenus = updatemenus)



# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="buttons/relayout")
chart_link

Update Button

The '"update"' method should be used when modifying the data and layout sections of the graph. This example demostrates how to update which traces are diplayed while simultaneously updating layout attributes such as the chart title and annotations.

library(plotly)
library(quantmod)

getSymbols("YHOO",src='yahoo')

df <- data.frame(Date=index(YHOO),coredata(YHOO))

high_annotations <- list(
  x=df$Date[df$YHOO.High == max(df$YHOO.High)], 
  y=max(df$YHOO.High),
  xref='x', yref='y',
  text=paste0('High: $',max(df$YHOO.High)),
  ax=0, ay=-40
)

low_annotations <- list(
  x=df$Date[df$YHOO.Low == min(df$YHOO.Low)], 
  y=min(df$YHOO.Low),
  xref='x', yref='y',
  text=paste0('Low: $',min(df$YHOO.Low)),
  ax=0, ay=40
)

# updatemenus component
updatemenus <- list(
  list(
    active = -1,
    type= 'buttons',
    buttons = list(
      list(
        label = "High",
        method = "update",
        args = list(list(visible = c(FALSE, TRUE)),
                    list(title = "Yahoo High",
                         annotations = list(c(), high_annotations)))),
      list(
        label = "Low",
        method = "update",
        args = list(list(visible = c(TRUE, FALSE)),
                    list(title = "Yahoo Low",
                         annotations = list(low_annotations, c() )))),
      list(
        label = "Both",
        method = "update",
        args = list(list(visible = c(TRUE, TRUE)),
                    list(title = "Yahoo",
                         annotations = list(low_annotations, high_annotations)))),
      list(
        label = "Reset",
        method = "update",
        args = list(list(visible = c(TRUE, TRUE)),
                    list(title = "Yahoo",
                         annotations = list(c(), c())))))
  )
)

p <- df %>%
  plot_ly(type = 'scatter', mode = 'lines') %>%
  add_lines(x=~Date, y=~YHOO.High, name="High",
            line=list(color="#33CFA5")) %>%
  add_lines(x=~Date, y=~YHOO.Low, name="Low",
            line=list(color="#F06A6A")) %>%
  layout(title = "Yahoo", showlegend=FALSE,
         xaxis=list(title="Date"),
         yaxis=list(title="Price ($)"),
         updatemenus=updatemenus)


# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="buttons/update")
chart_link

Animate Button

Animations are currently only available in the development package and offline.

Style Buttons

When adding buttons to Plotly charts, users have the option of styling the color, font, padding, and position of the buttons. The example below demostrates hot to apply different styling options. See all updatemenus styling attributes here: https://plot.ly/r/reference/#layout-updatemenus.

library(plotly)

# make sure you have a Mapbox token https://www.mapbox.com/help/create-api-access-token/
# Sys.setenv('MAPBOX_TOKEN' = 'your mapbox token') 

# read in wind turbines and farms data
df_wind = read.csv('https://plot.ly/~datasets/2805.csv')
df_farms = read.csv('https://plot.ly/~jackp/17256.csv')

# subset and clean data
df_sub <- subset(df_wind, manufac != "unknown", select=c(lat_DD, long_DD, manufac))
df_farms$Longitude = as.numeric(gsub("'", "", df_farms$Longitude))
df_farms$Wind.Farm = gsub("^((\\w+\\W+){2}).*","\\1",df_farms$Wind.Farm)
rm(df_wind)


# location buttons
usa <- list(method = "relayout",
            args = list(list(mapbox.center.lat = median(df_sub$lat_DD),
                             mapbox.center.lon = median(df_sub$long_DD),
                             mapbox.zoom = 3)),
            label = "USA")

buttons <- function(i) {
  list(method = "relayout",
       args = list(list(mapbox.center.lat = df_farms$Latitude[i],
                        mapbox.center.lon = df_farms$Longitude[i],
                        mapbox.zoom = 9)),
       label = df_farms$Wind.Farm[i]) 
}

# map style buttons
basic <- list(method = "relayout",
              args = list(list(mapbox.style = "basic")),
              label = "Basic")

dark <- list(method = "relayout",
             args = list(list(mapbox.style = "dark")),
             label = "Dark")

satellite <- list(method = "relayout",
                  args = list(list(mapbox.style = "satellite")),
                  label = "Satellite")  

# plot scattermapbox with buttons 
p <- plot_mapbox(df_sub, lat = ~lat_DD, lon = ~long_DD, mode = 'scattermapbox',
                 split = ~manufac, size=3) %>%
  add_annotations(x = 0.05, y = 0.05,
                  text = "All US wind turbines (scroll to zoom)",
                  xref = "page",
                  yref = "page",
                  showarrow = FALSE,
                  font = list(color = 'magenta',
                              size = 14)) %>%
  layout(plot_bgcolor = 'black', 
         paper_bgcolor = 'black', 
         mapbox = list(center = list(lat = median(df_sub$lat_DD), 
                                     lon = median(df_sub$long_DD)), 
                       zoom = 3, style = 'dark'),
         updatemenus = list(

           list(type='buttons',
                direction = "right",
                xanchor = 'center',
                yanchor = "top",
                pad = list('r'= 0, 't'= 10, 'b' = 10),
                x = 0.5,
                y = 1,
                showactive = FALSE,
                buttons=list(usa, buttons(1),
                             buttons(2), buttons(3), 
                             buttons(4))),

           list(type='buttons',
                direction = "right",
                xanchor = 'center',
                yanchor = "top",
                pad = list('r'= 0, 't'= 10, 'b' = 10),
                x = 0.5,
                y = 0.935,
                showactive = FALSE,
                buttons=list(buttons(6), buttons(7),
                             buttons(8), buttons(9))),

           list(type='buttons',
                direction = "right",
                yanchor = "bottom",
                x = 1,
                y = 0,
                buttons=list(dark,basic,satellite)))) 


# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = plotly_POST(p, filename="buttons/wind-turbine")
chart_link

Reference

See https://plot.ly/r/reference/#layout-updatemenus for more information and options!

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.