Purrr output (listed ggplot) on Shiny?

Hello all,

Is there a way to print listed ggplot (created through purrr) items on Shiny?

I'd like to print 30+ plots one after another without creating a for loop to pre-define the number of plots to be made.

I tried to play around with renderUI but wasn't too successful.

Thank you!

Maybe something like this :

library(tidyverse)
library(shiny)

plotList <- mtcars %>%
   mutate(cyl = as.factor(cyl)) %>%
   group_by(cyl) %>%
   nest() %>%
   mutate(plot = map2(data, cyl, ~ggplot(data = .x) +
                          geom_point(aes(y = hp, x = disp)) +
                          ggtitle(.y)))

ui <- fluidPage(
 mainPanel(
    uiOutput("cylPlots")
 )
)

server <- function(input, output) {
   
  observe({
      for (thisRow in 1:nrow(plotList)) {
              plotname <- paste("cylPlot_", plotList[thisRow,"cyl"] %>% pull(), sep = "")
              insertUI(selector = "#cylPlots",
                       where = "beforeEnd",
                       ui =  fluidRow(plotOutput(outputId = plotname,  height = "200px"))
              )
              output[[plotname]] <- renderPlot({
                  plotList[thisRow, "plot"] %>% pull()
              })
      }
  })
}

shinyApp(ui = ui, server = server)

I'm personnaly using this approach to plot an unknown number of automatically generated plots depending if they're (or not) selected in a table (using DT)

I guess the final for loop could be converted to something more purrr-ish, but for such verbose content, I find it easier this way.

if you want a single layout use ggedit::gglist, this will print your list in a layout automatically.

library(ggedit)

#lets say your list of ggplots is called p
as.gglist(p)

if you want to use them individually you can use slickR to place them in a slider in shiny. an example how to do that can be found here.

1 Like