Shiny: unwanted space added by plotOutput() and/or renderPlot()

前端 未结 2 779
抹茶落季
抹茶落季 2020-12-18 09:30

Either plotOutput or renderPlot seems to add a bunch of extra white space around a plot. I\'ve added background colours to the plot and the layout

2条回答
  •  轮回少年
    2020-12-18 09:50

    The space is added by the grid layout engine, not by anything in shiny. Grid adds the white space because ggplot has asked it to maintain the aspect ratio of the plot, to make sure the circle is round.

    Here is how you can see this. First, let's draw the plot the regular way, but let's manually convert to a grob first.

    g <- ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
      geom_bar(width = 1, stat = "identity") +
      coord_polar("y", start=0) +
      theme(plot.background = element_rect(fill = "lightblue"))
    
    library(grid)
    grob <- ggplotGrob(g)
    grid.newpage()
    grid.draw(grob)
    

    This will generate plots with whitespace either on the sides or above/below, depending on the shape of the enclosing window:

    Now let's turn off the aspect-ratio enforcement and plot again:

    grob$respect <- FALSE # this switches of the fixed aspect ratio
    grid.newpage()
    grid.draw(grob)
    

    Now there is no white space, but also the circle isn't round.

    You'll have to put the plot into an enclosing container that can provide necessary white space on the right and bottom. This is possible with grid if you're willing to give the plot a fixed size, by putting the plot into a table with empty space to the side and bottom:

    library(grid)
    library(gtable)
    # need to play around to find numbers that work
    plotwidth = unit(6.1, "inch")
    plotheight = unit(5, "inch")
    
    grob <- ggplotGrob(g)
    mat <- matrix(list(grob, nullGrob(), nullGrob(), nullGrob()), nrow = 2)
    widths <- unit(c(1, 1), "null")
    widths[1] <- plotwidth
    heights <- unit(c(1, 1), "null")
    heights[1] <- plotheight
    gm <- gtable_matrix(NULL, mat, widths, heights)
    grid.newpage()
    grid.draw(gm)
    

    The downside of this approach is that now, if the plot window is too small, the plot will not be resized but instead will be cut off:

    I'm not sure how to get the plot to scale to the largest possible size that still fits within the window.

提交回复
热议问题