如何创建在 R 中使用 ggplot2 生成的列表中排列的图?

如果我们有两个使用 ggplot2 生成的图并排列在一个列表中,那么我们可以使用 ggarrange 函数创建它们。例如,如果我们有两个对象 p1 和 p2 存储在名为 LIST 的列表中,那么可以使用命令 ggarrange(plotlist=LIST,widths=c(2,1) 在绘图窗口中创建这些绘图,标签=c("散点图","Hist"))

示例

考虑以下数据框 -

set.seed(21)
x<−rnorm(20)
y<−rnorm(20)
df<−data.frame(x,y)
df
输出结果
       x          y
1 0.793013171   0.39299759
2 0.522251264   0.03675713
3 1.746222241   -1.03208366
4 −1.271336123 −1.26486147
5 2.197389533  −0.22696529
6 0.433130777   0.74558930
7 −1.570199630  0.33281918
8 −0.934905667 −1.12404046
9 0.063493345   −0.70613078
10 −0.002393336 −0.72754386
11 −2.276781240 −1.83431439
12 0.757412225  −0.40768794
13 −0.548405554 0.02686119
14 0.172549478 0.91162864
15 0.562853068 1.63434648
16 1.511817959 0.06068561
17 0.659025169 1.84757253
18 1.122028075 0.08012495
19 −0.784641369 1.41855588
20 −0.425692289 1.45861594

加载 ggplot2 包并创建绘图 -

示例

library(ggplot2)
Scatterplot<−ggplot(df,aes(x,y))+geom_point()
Hist_of_x<−ggplot(df,aes(x))+geom_histogram(bins=30)
List<−list(Scatterplot,Hist_of_x)
ggarrange(plotlist=List,widths=c(2,1),labels=c("Scatter","Hist"))
输出结果