Sliders in R

How to add slider controls to your plots 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.

Basic Slider Control

library(plotly)

df <- data.frame(x = c("1", "2", "3", "4", "5"), 
                 y = c("1", "1", "1", "1", "1")) 

# create steps for slider
steps <- list(
  list(args = list("marker.color", "red"), 
                    label = "Red", 
                    method = "restyle", 
                    value = "1"
                    ),
  list(args = list("marker.color", "green"), 
                    label = "Green", 
                    method = "restyle", 
                    value = "2"
                    ),
  list(args = list("marker.color", "blue"), 
                    label = "Blue", 
                    method = "restyle", 
                    value = "3"
                    )
  )

fig<- df 
fig <- fig %>% plot_ly(x = ~x, y = ~y,
          mode = "markers", 
          marker = list(size = 20,
                        color = 'green'), 
          type = "scatter") 
fig <- fig %>% layout(title = "Basic Slider",
         sliders = list(
           list(
             active = 1, 
             currentvalue = list(prefix = "Color: "), 
             pad = list(t = 60), 
             steps = steps))) 

fig

Sine Wave Slider

library(plotly)

x <- seq(0,10, length.out = 1000)

# create data
aval <- list()
for(step in 1:11){
  aval[[step]] <-list(visible = FALSE,
                      name = paste0('v = ', step),
                      x=x,
                      y=sin(step*x))
}
aval[3][[1]]$visible = TRUE

# create steps and plot all traces
steps <- list()
fig <- plot_ly()
for (i in 1:11) {
 fig <- add_lines(fig,x=aval[i][[1]]$x,  y=aval[i][[1]]$y, visible = aval[i][[1]]$visible, 
                 name = aval[i][[1]]$name, type = 'scatter', mode = 'lines', hoverinfo = 'name', 
                 line=list(color='00CED1'), showlegend = FALSE)

  step <- list(args = list('visible', rep(FALSE, length(aval))),
               method = 'restyle')
  step$args[[2]][i] = TRUE  
  steps[[i]] = step 
}  

# add slider control to plot
fig <- fig %>%
  layout(sliders = list(list(active = 3,
                             currentvalue = list(prefix = "Frequency: "),
                             steps = steps)))

fig

Mulitple Slider Controls

library(plotly)

df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/globe_contours.csv')
df$id <- seq_len(nrow(df))

library(tidyr)
d <- df %>%
  gather(key, value, -id) %>%
  separate(key, c("l", "line"), "\\.") %>%
  spread(l, value)

geo <- list(
  showland = TRUE,
  showlakes = TRUE,
  showcountries = TRUE,
  showocean = TRUE,
  countrywidth = 0.5,
  landcolor = 'rgb(230, 145, 56)',
  lakecolor = 'rgb(0, 255, 255)',
  oceancolor = 'rgb(0, 255, 255)',
  projection = list(
    type = 'orthographic',
    rotation = list(
      lon = -100,
      lat = 40,
      roll = 0
    )
  ),
  lonaxis = list(
    showgrid = TRUE,
    gridcolor = toRGB("gray40"),
    gridwidth = 0.5
  ),
  lataxis = list(
    showgrid = TRUE,
    gridcolor = toRGB("gray40"),
    gridwidth = 0.5
  )
)

## add custom events

# dropdown
projections = data.frame(type = c("equirectangular", "mercator", "orthographic", "natural earth","kavrayskiy7", 
                                  "miller", "robinson", "eckert4", "azimuthal equal area","azimuthal equidistant", 
                                  "conic equal area", "conic conformal", "conic equidistant", "gnomonic", "stereographic", 
                                  "mollweide", "hammer", "transverse mercator", "albers usa", "winkel tripel"))

all_buttons <- list()
for (i in 1:length(projections[,])) { 
  all_buttons[[i]] <- list(method = "relayout",
                           args = list(list(geo.projection.type = projections$type[i])),
                           label = projections$type[i])
}

# sliders
lon_range = data.frame(seq(-180, 180, 10))
lat_range = data.frame(seq(-90, 90, 10))
colnames(lon_range) <- "x"
colnames(lat_range) <- "x"

all_lat <- list()
for (i in 1:length(lat_range[,])) { 
  all_lat[[i]] <- list(method = "relayout",
                       args = list(list(geo.projection.rotation.lat = lat_range$x[i])),
                       label = lat_range$x[i])
}

all_lon <- list()
for (i in 1:length(lon_range[,])) {  
  all_lon[[i]] <- list(method = "relayout", 
                       args = list(list(geo.projection.rotation.lon = lon_range$x[i])),
                       label = lon_range$x[i]) 
} 

# annotations
annot <- list(x = 0, y=0.8, text = "Projection", yanchor = 'bottom', 
              xref = 'paper', xanchor = 'right',
              showarrow = FALSE)


# original d3-globe with contours
fig<- plot_geo(d) 
fig <- fig %>% group_by(line) 
fig <- fig %>% add_lines(x = ~lon, y = ~lat, color = ~line, colors = 'Reds') 
fig <- fig %>% layout(
  showlegend = FALSE, geo = geo
)

# plot with custom events
fig<- fig
fig <- fig %>% layout(annotations = annot,
                      updatemenus = list(list(active = 2, x = 0, y = 0.8, 
                                              buttons=all_buttons)),
                      sliders = list(

                        list(
                          active = (length(lon_range[,])-1)/2, 
                          currentvalue = list(prefix = "Longitude: "), 
                          pad = list(t = 20), 

                          steps = all_lon),

                        list(
                          active = (length(lat_range[,])-1)/2, 
                          currentvalue = list(prefix = "Latitude: "), 
                          pad = list(t = 100), 

                          steps = all_lat)))

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)