从网格布局引擎更改 R ggplots 周围的空格

Change whitespace around R ggplots from grid layout engine

在 R 中,图形引擎会在未填满容器大小的打印图周围添加白色space。此答案中提供了大量代码示例:

我在这里重复其中的一些:

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)

我想知道是否有任何方法可以将此填充物 space 设置为特定颜色或透明,而不是白色 space?如果未设置绘图 aspect.ratio 则不会出现此问题,但我希望设置纵横比!

实现所需结果的一种选择是使用所需的填充颜色绘制 rectGrob 并在其上绘制 ggplot:

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))