Indexing Tables From Plotly output

Submitted by our Working Group member Julia Piaskowski. We discussed this a bit in Trouble Shooting, but its relevant to anyone using Plotly. Thanks Julia! :

Plotly is an enormously handy set of interactive plotting function that have been developed for R, Python and D3.js. One very useful feature of plotly is “event_data” where users are able to click on or select parts of the plot for more information or to create new plots from the selected output. There’s several types of event_data, but I am focusing on “plotly_selected” where a user selects several points using a lasso or box selection tool.

I am using plotly in R/Shiny to create an interactive plot. The idea seemed simple: generate a bivariate scatterplot colored by a factor in the data set. Users should be able to select a region of interest, and the full data from those observations will be presented in a table. However, the indexing was not working using the usual mydata[rows,columns] method – it worked for some observations, but not others.

The problem was that the data were being unstacked by the grouping variable used to color the plot, essentially creating a separate a rowXcolumn object for each level of the grouping variable.

The solution was slightly complicated, requiring both subsetting the object AND the plotly event_data. A small example is shown below. A bigger demo is at:


# Make data
mydata<-data.frame(Name = replicate(10,paste(sample(LETTERS,3),collapse = “”)),
a = 1:10,b = sample(1:100,10),c = rep(c(“up”,”down”),5),
d = paste0(“secret_data”,1:10))

# Generate the Display (ultra simple in this example)

ui <- fluidPage(
column(6, tags$h3(“Basic Plot”), plotlyOutput(“Plot1”, height = “300px”)) ,
column(6, tags$h3(“Selected Output”), tableOutput(“clickTable”))

# server info
server <- function(input, output){

output$Plot1 %>%
dragmode = “select”)

output$clickTable <-renderTable({ <- event_data(“plotly_selected”, source = “subset”)

if(is.null( == T) return(“Choose individuals by selecting a region in the scatterplot”) else {

# Get index from each group
# This is the where indexing was failing previously. The scripts must reference both the group variable (called the “curveNumber” AND the observation (the “pointNumber”). Not to be outdone by something more confusing, plotly is going against R convention and starting their indexing at zero – hence the use of “0” for the “up” group, and why a value of 1 is added to each “pointNumber”. <- subset(mydata, c == “up”)[subset(, curveNumber == 0)$pointNumber + 1,] <- subset(mydata, c == “down”)[subset(, curveNumber == 1)$pointNumber + 1,]

# Combine and make table
table.subset <- rbind(,


shinyApp(ui = ui, server = server)