首页 > 解决方案 > 从网格布局引擎更改 R ggplots 周围的空白

问题描述

在 R 中,如果打印的图没有填满容器的大小,图形引擎会在打印的图周围添加空格。此答案中提供了相当多的代码示例: https ://stackoverflow.com/a/47703716/3330437

我在这里重复其中一些:

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)

情节周围的空白图像

我想知道是否有任何方法可以将此填充空间设置为特定颜色,而不是空白,或者使其透明?如果未设置 plot aspect.ratio,则不会出现此问题,但我想设置一个宽高比!

标签: rggplot2graphicsrstudio

解决方案


实现所需结果的一种选择是rectGrob使用所需的填充颜色绘制 a 并在其上绘制 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))


推荐阅读