Change whitespace around R ggplots from grid layout engine

Viewed 68

In R, the graphics engine adds whitespace around plots that are printed if they do not fill up the size of the container. Considerable code examples are provided in this answer: https://stackoverflow.com/a/47703716/3330437

and I repeat some of them here:

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)

image of whitespace around plot

I am wondering if there is any way that, rather than whitespace, this filler space can be set to a particular color, or made to be transparent? The issue does not arise if the plot aspect.ratio is not set, but I would like to have a set aspect ratio!

1 Answers

One option to achieve your desired result would be to draw a rectGrob with the desired fill color and drawing the ggplot on top of it:

set.seed(42)

animals <- as.data.frame(
  table(
    Species =
      c(
        rep("Moose", sample(1:100, 1)),
        rep("Frog", sample(1:100, 1)),
        rep("Dragonfly", sample(1:100, 1))
      )
  )
)

library(ggplot2)
library(grid)

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", color = "lightblue"))


grob <- rectGrob(gp = gpar(fill = "lightblue", col = "lightblue"))
grid.newpage()
grid.draw(grob)
grid.draw(ggplotGrob(g))

Related