7

I'd like to put the legend to one of my graphs in the sidebar of my shiny fluid-page. I had two ideas for this:

  1. Get the legend grob via ggplotly and put in sidebar or
  2. Render a legend with the same colors and no plot in the sidebar.
    Unfortunately I'm not sure how to do either of these.

Any ideas?
Example shiny below.

library(plotly, shiny) 

data <- ChickWeight
ag_data <- aggregate(data$weight,
                     list(time = data$Time, diet = data$Diet),
                     mean)  

ui <- fluidPage(
  
  sidebarPanel("Put Legend Here"),
  mainPanel(
    plotlyOutput("chick_weight")
  )

) # End fluid page

server <- function(input, output) {
  
  output$chick_weight <- renderPlotly({
    plot_ly(
      x = c(ag_data$time),
      y = c(ag_data$x),
      type = "scatter",
      mode = "lines",
      split = c(ag_data$diet),
      showlegend = FALSE
    )
  })
  
} # End server function

shinyApp(ui = ui, server = server)

enter image description here

Dave2e
  • 22,192
  • 18
  • 42
  • 50
Lauren Dahlin
  • 159
  • 1
  • 8
  • 1
    As far as I'm aware, this won't work for plotly, but @Tyler Rinker on this answer shows how to just get a legend for just a ggplot,: https://stackoverflow.com/questions/12041042/how-to-plot-just-the-legends-in-ggplot2 I thought maybe this could be of use for some in the future if they are fine not using plotly. – Silentdevildoll Nov 11 '21 at 19:10

0 Answers0