Interactive Plotly

The idea is about using package plotly for producing interactive plots for a Shiny application.
Official documentation about plotly is superb. Nevertheless, as this graphics grammar, within the R community is not as spread as ggplot is, few topics require a bit of extra research.

Andrea Spano andreaspano.github.io (Quantide)www.quantide.com
2021-04-04

Intro

Given

I would like to:

I will be using the classic iris data for this example.

Step 1:

Load the required packages

Step 2:

Add a unique id to data

data <- iris %>% mutate ( id = 1:n())

Step 3:

Transform data into a ShareData object

data <- data %>% highlight_key(~id) 

Step 4:

Build your plots as you would normally do

pl1 <- plot_ly(data, 
               x = ~ Sepal.Length, y = ~Sepal.Width, 
               type = 'scatter', mode = 'markers', 
               marker = list ( color = 'green')) %>% 
  layout(showlegend=F)
               
pl2 <- plot_ly(data, 
               x = ~Petal.Length, y = ~Petal.Width, 
               type = 'scatter', mode = 'markers',
               marker = list ( color = 'blue')) %>% 
  layout(showlegend=F)

Step 5:

Bind your plots into a single subplot

pl <- subplot(pl1, pl2, nrows = 2)

Step 6:

Link the plots

pl <- pl %>% 
  highlight(on = "plotly_select", off = 'plotly_doubleclick', 
            opacityDim = .5, 
            selected = attrs_selected(marker = list ( size = 20, color = 'orange')))

Step 7:

Display results

pl

Corrections

If you see mistakes or want to suggest changes, please create an issue on the source repository.

Citation

For attribution, please cite this work as

Spano (2021, April 4). andreaspano blog: Interactive Plotly. Retrieved from https://andreaspano.github.io/posts/2021-02-27-interactive-plotly/

BibTeX citation

@misc{spano2021interactive,
  author = {Spano, Andrea},
  title = {andreaspano blog: Interactive Plotly},
  url = {https://andreaspano.github.io/posts/2021-02-27-interactive-plotly/},
  year = {2021}
}