如何建立使用 R 中 ggplot2 生成的、以列表安排的繪圖?


如果我們有兩個使用 ggplot2 生成的繪圖,並以列表形式排列,那麼我們可以使用 ggarrange 函式建立它們。例如,如果我們有兩個物件 p1 和 p2 儲存在名為 LIST 的列表中,那麼可以使用命令 ggarrange(plotlist=LIST,widths=c(2,1),labels=c("散點圖","直方圖")) 在繪圖視窗中建立這些繪圖

示例

考慮以下資料框架——

 即時演示

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"))

輸出

更新日期: 08-Feb-2021

429 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告資訊
© . All rights reserved.