首页 > 解决方案 > 控制 ggplot 图的大小以匹配第二个图

问题描述

我希望彼此重叠的两个地块具有相同的大小。问题是刻度标签的长度不同,因此图没有对齐。仅仅缩小字体并不是一个解决方案,因为它对读者不友好。必须有一种方法可以说明在 ggplot 中的情节应该有多大。我只想手动控制绘图的大小,无论我是否必须绘制条形图或条形图和箱线图等。我该如何做到这一点?

 library(ggplot2)
library(grid)
library(gridExtra)

df1 <- data.frame(a = as.factor(1:20), b = runif(20, 500000, 900000))
df2 <- data.frame(a = as.factor(1:20), c = rnorm(2000))

plot1 <- ggplot(df1, aes(x = a, y =b)) + geom_bar(stat = "identity")
plot2 <- ggplot(df2, aes(x = a, y =c)) + geom_boxplot()

grid.arrange(plot1,
             plot2,
             ncol = 1)

这是我的例子: 在此处输入图像描述

标签: rggplot2

解决方案


正如提到的评论之一,包cowplot具有您需要的功能。

library(ggplot2)
library(cowplot)

df1 <- data.frame(a = as.factor(1:20), b = runif(20, 5, 9))
df2 <- data.frame(a = as.factor(1:20), b = runif(20, 50000, 90000))

plot1 <- ggplot(df1, aes(x = a, y =b)) + geom_bar(stat = "identity")
plot2 <- ggplot(df2, aes(x = a, y =b)) + geom_bar(stat = "identity")

#see ?plot_grid for more details
plot_grid(plot1,plot2,ncol = 1, align = "v", rel_heights = c(.7, .3))

reprex 包(v0.2.1)于 2019 年 1 月 12 日创建


推荐阅读