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

时间:2019-07-05 15:23:57

标签: r ggplot2 resize facet-wrap

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

例如有一个2x2的图,并且每个帧都应该是二次的,高度和宽度为400x400像素,您不能将整个图的尺寸设置为800x800,因为仍然有轴文本(由于“比例尺,它们的长度可能会有所不同facet_wrap(〜variable,scales =“ free_y”))中的=“ free_y”命令。这将导致“压缩”,而不是二次帧大小。

IF(ISBLANK([type]);"C")

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

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式对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")):

enter image description here

现在,如果您还希望将条带(深色框中的面板标题显示为文本)包含在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)

如下所示:

enter image description here