使用 ggplot2 和 geom_boxplot 手动定义帧的大小

Manually define size of frame using ggplot2 and geom_boxplot

如何在使用 ggplot2 绘制多个箱线图时手动定义单个图形的框架大小?

如果你有一个 2x2 的图,每个帧应该是 400x400 像素高度和宽度的二次方,你不能将整个图的尺寸设置为 800x800,因为仍然有轴文本(并且由于 "scales="free_y" facet_wrap(~variable,scales="free_y") 中的命令。这导致 "squeezed" 而不是二次帧大小。

p<-ggplot(data=data.frame,aes(x=x,y=value))+
geom_boxplot(size=0.1, fill="grey90")+
geom_point(aes(x=x, y=value, fill="black"),inherit.aes=FALSE, colour="red", size=2, position=position_jitterdodge(jitter.width = 0.25), show.legend=FALSE)+
facet_wrap(~variable,scales="free_y")+
theme_bw()

预期结果:图框应始终为用户定义的高度和宽度的二次方。

您可以通过以下方式使用 gtables 执行此操作。首先我们要建一个地块。

library(ggplot2)
library(grid)
# I don't have your data so I'll just use the diamonds dataset
p <- ggplot(diamonds, aes(x = cut, y = price)) +
  geom_boxplot() +
  facet_wrap(~ clarity, scales = "free_y")

然后我们将绘图转换为 gtable,获取面板位置并根据自己的喜好调整宽度和高度。

gt <- ggplotGrob(p)
# Usually panels don't span multiple cells in the table, so we can take the
# left ("l") and top ("t") positions of the panels.
panel_x <- panel_cols(gt)[,"l"]
panel_y <- panel_rows(gt)[,"t"]
gt$widths[panel_x]  <- unit(400/72, "inches")
gt$heights[panel_y] <- unit(400/72, "inches")

grid.newpage(); grid.draw(gt)

不幸的是,unit() 函数不允许您以像素为单位指定尺寸,因此我假设您的输出分辨率为每英寸 72 像素。查看 ?unit 查看选项。

编辑:

这就是上面的样子(为简洁起见 unit(100/72, "inches")):

现在,如果您还希望在 400x400 框中包含条带(看起来像深色框中的面板标题的文本),您可能需要沿着行找到条带位置并从单位中减去这些你供应。

gt <- ggplotGrob(p)
panel_x <- panel_cols(gt)[,"l"]
panel_y <- panel_rows(gt)[,"t"]
strip_y <- unique(gt$layout$t[grepl("strip", gt$layout$name)])
gt$widths[panel_x]  <- unit(100/72, "inches")
gt$heights[panel_y] <- unit(100/72, "inches") - gt$heights[strip_y]

grid.newpage(); grid.draw(gt)

如下所示: