Is it possible to link legends from separate plotly plots in Shiny? I know you can link plots using click events, such as clicking on certain data points within a graph, but I've not found any info on linking legends.
I will have a dynamic number of plots that will all have the same legend items, so it would be nice for the user to click/unclick a legend item to show/hide a line on all the linked plots. I originally had a nice linked single legend using plotly subplots, but I wasn't able to arrange the positioning of the plots, their titles, and the single legend nicely on the page, hence I'm going back to having separate plotly plots.
I've inserted an example shiny app below as a base for suggestions on how to link the legends:
library(shiny)
library(plotly)
ui <- fluidPage(
plotlyOutput("plot1"),
plotlyOutput("plot2")
)
server <- function(input, output) {
output$plot1 <- renderPlotly({
trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)
data <- data.frame(x, trace_0, trace_1, trace_2)
fig <- plot_ly(data, x = ~x)
fig <- fig %>% add_trace(y = ~trace_0, name = 'trace 0',mode = 'lines')
fig <- fig %>% add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines+markers')
fig <- fig %>% add_trace(y = ~trace_2, name = 'trace 2', mode = 'markers')
})
output$plot2 <- renderPlotly({
trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)
data <- data.frame(x, trace_0, trace_1, trace_2)
fig <- plot_ly(data, x = ~x)
fig <- fig %>% add_trace(y = ~trace_0, name = 'trace 0',mode = 'lines')
fig <- fig %>% add_trace(y = ~trace_1, name = 'trace 1', mode = 'lines+markers')
fig <- fig %>% add_trace(y = ~trace_2, name = 'trace 2', mode = 'markers')
})
}
# Run the application
shinyApp(ui = ui, server = server)