简体   繁体   中英

Dynamic grid plots in shiny R

I am trying to generate the grids of graphs in shiny from list of plot objects. Currently all the graphs displays the last plot in the plot object list.

I want to display plots from plots list in grid format.

shinyServer(function(input, output) {

  # Insert the right number of plot output objects into the web page
  output$plots <- renderUI({
    plot_output_list <<- lapply(1:length(plots), function(i) {
      plotname <- paste("plot", i , sep="")
      plotOutput(plotname, height = 280, width = 250)
    })

    # Convert the list to a tagList - this is necessary for the list of items
    # to display properly.
    do.call(tagList, plot_output_list)
  })

  # Call renderPlot for each one. Plots are only actually generated when they
  # are visible on the web page.
  max_plots = length(plots)
  for (i in 1:length(plots)) {
    # Need local so that each item gets its own number. Without it, the value
    # of i in the renderPlot() will be the same across all instances, because
    # of when the expression is evaluated.
    local({

      plotname <- paste("plot", i , sep="")
      plotnames[i] <<- plotname
      output[[plotname]] <- renderPlot({
        plots[[i]] # plots - list of plot objects which I am trying to display as grids

       })
    })
  }
})

As @vongo is saying ggplot2 is a really awesome package which i would encourage you to use. But if you want to organize your html in a grid the bootstrap grid system is really good for this. You can do something like this:

require(shiny)

ui <- shinyUI(fluidPage(
  uiOutput('plots')
))

server <- shinyServer(function(input, output) {

  plots <- lapply(1:10, function(i){
    plot(runif(50),main=sprintf('Plot nr #%d',i)) 
    p <- recordPlot()
    plot.new()
    p
  })
  n.col <- 3

  output$plots <- renderUI({
    col.width <- round(12/n.col) # Calculate bootstrap column width
    n.row <- ceiling(length(plots)/n.col) # calculate number of rows
    cnter <<- 0 # Counter variable

    # Create row with columns
    rows  <- lapply(1:n.row,function(row.num){
        cols  <- lapply(1:n.col, function(i) {
          cnter    <<- cnter + 1
          plotname <- paste("plot", cnter, sep="")
          column(col.width, plotOutput(plotname, height = 280, width = 250))
        }) 
        fluidRow( do.call(tagList, cols) )
    })

    do.call(tagList, rows)
  })

  for (i in 1:length(plots)) {
    local({
      n <- i # Make local variable
      plotname <- paste("plot", n , sep="")
      output[[plotname]] <- renderPlot({
        plots[[n]]
      })
    })
  }
})

shinyApp(ui=ui,server=server)

You could consider using ggplot2 instead of basic plot, and then (Cf. this post on R cookbook) use the multiplot function :

# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols:   Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  library(grid)

  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)

  numPlots = length(plots)

  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                    ncol = cols, nrow = ceiling(numPlots/cols))
  }

 if (numPlots==1) {
    print(plots[[1]])

  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}

This would allow you to treat your group of plots as a single one on Shiny server side, something like :

shinyServer(function(input, output) {
  # Insert the right number of plot output objects into the web page
  output$plots <- renderPlot({
    plot_output_list <- sapply(1:length(plots), function(i) {
      plotname <- paste("plot", i , sep="")
      plotOutput(plotname, height = 280, width = 250)
    })
    multiplot(plot_output_list)
  })
})

But maybe I didn't understand all your constraints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM