R markdown with rotating gallery-like slides for each plot?

Viewed 101

So for example suppose I have these three plots

p1 <- iris%>%ggplot(aes(x=Sepal.Length,y=Sepal.Width))+geom_point()
p2 <- iris%>%ggplot(aes(x=Sepal.Length,y=Sepal.Width))+geom_bar(stat="identity",  width = 1, fill="#98ff98")
p3 <- iris%>%ggplot(aes(x=Species,y=Sepal.Width))+geom_bar(stat="identity",  width = 1, fill="blue")

So instead printing each plot out separately in the html markdown so that the user has to scroll down to view each of the figures, is there a way to output some sort of ui where the left hand side is the plot and right hand side are the selection for the plots. Then the user can simply select which plot to view and it will appear on the left. Is this possible? The reason why I ask is because often I can have 10-20 figures per comparison that can get unwieldy very fast and I think this would be an excellent way to organize them.

thanks!

1 Answers

Maybe something like this can get you started

library(shiny)

# create a list of plots
plots <- list(
  p1 = iris%>%ggplot(aes(x=Sepal.Length,y=Sepal.Width))+geom_point(),
  p2 = iris%>%ggplot(aes(x=Sepal.Length,y=Sepal.Width))+geom_bar(stat="identity",  width = 1, fill="#98ff98"),
  p3 = iris%>%ggplot(aes(x=Species,y=Sepal.Width))+geom_bar(stat="identity",  width = 1, fill="blue")
)


# put names of plots in a list in sidebar
ui <- fluidPage(sidebarLayout(
  sidebarPanel(tags$ul(purrr::map(names(plots), ~tags$li(actionLink(paste0("show", .), .))))),
  mainPanel(plotOutput("currentplot"))
))

server <- function(input, output, session) {
  # draw the first plot by default
  current_plot <- reactiveVal(plots[[1]]);
  
  # set up observers for each of the action links in the UI
  purrr::map(names(plots), function(p) {
    observeEvent(input[[paste0("show",p)]], {
      # set current plot
      current_plot(plots[[p]])
    })
  })
  
  # render whatever the current plot is
  output$currentplot <- renderPlot(current_plot())
    
}

shinyApp(ui, server)

This will give you a list of plots on the left and will draw which ever you click on on the right.

you could probably make this more efficient if you wanted to write some javascript, but this at least gives a basic idea of how it might work.

Related