Buttons in R

How to add buttons in R with Plotly.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

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

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


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

fig

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

library(plotly)

fig <- 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
fig <- fig %>% layout(
  xaxis = list(domain = c(0.1, 1)),
  yaxis = list(title = "y"),
  updatemenus = list(chart_types,color_types),
  annotations = annot)

fig

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

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

fig

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)

d <- quantmod::getSymbols("AAPL")

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

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

low_annotations <- list(
  x=df$Date[df$AAPL.Low == min(df$AAPL.Low)], 
  y=min(df$AAPL.Low),
  xref='x', yref='y',
  text=paste0('Low: $',min(df$AAPL.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 = "Apple High",
                         annotations = list(c(), high_annotations)))),
      list(
        label = "Low",
        method = "update",
        args = list(list(visible = c(TRUE, FALSE)),
                    list(title = "Apple Low",
                         annotations = list(low_annotations, c() )))),
      list(
        label = "Both",
        method = "update",
        args = list(list(visible = c(TRUE, TRUE)),
                    list(title = "Apple",
                         annotations = list(low_annotations, high_annotations)))),
      list(
        label = "Reset",
        method = "update",
        args = list(list(visible = c(TRUE, TRUE)),
                    list(title = "Apple",
                         annotations = list(c(), c())))))
  )
)

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


fig

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://plotly.com/r/reference/#layout-updatemenus.

Mapbox Access Token

To plot on Mapbox maps with Plotly you may need a Mapbox account and a public Mapbox Access Token. See our Mapbox Mafig Layers documentation for more information. If you're using a Chart Studio Enterprise server, please see additional instructions here.

library(plotly)

mapboxToken <- paste(readLines("../.mapbox_token"), collapse="")    # You need your own token

# Setting mapbox token for R environment 
Sys.setenv("MAPBOX_TOKEN" = mapboxToken)

# read in wind turbines and farms data
df_wind = read.csv('data/2805.csv')
df_farms = read.csv('https://plotly.com/~jackp/17256.csv', skipNul = TRUE)

# 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]) 
}

# mafig 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 
fig <- plot_mapbox(df_sub, lat = ~lat_DD, lon = ~long_DD, mode = 'scattermapbox',
                 split = ~manufac, size=3) 
fig <- fig %>% 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)) 
fig <- fig %>% 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)))) 
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))

fig

Reference

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

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)