ggplot2一頁(yè)多圖排版的簡(jiǎn)便方法

更好的閱讀體驗(yàn)>>

要想在同一頁(yè)面上排列多個(gè)ggplot2圖形,基本的R函數(shù)par()layout()是無(wú)效的。解決方案之一是使用 gridExtra包中的一些函數(shù)來排版多個(gè)圖形:

  • grid.arrange(),arrangeGrob()函數(shù)可以用來在同一頁(yè)面排版多個(gè)圖形;
  • marrangeGrob()函數(shù)可以用于在多個(gè)頁(yè)面排版多個(gè)圖形。

但是,這幾個(gè)函數(shù)并不能按照?qǐng)D形軸線排列整齊,只能是按圖形原樣依次排列(如下圖所示)。如果想多個(gè)圖按照軸線對(duì)齊排列,可以使用cowplot包中的plot_grid()函數(shù)。但是,cowplot 包并不包含在多個(gè)頁(yè)面排列多個(gè)圖形的功能。因此,解決方案就是使用ggpubr包中的ggarrange()函數(shù)來實(shí)現(xiàn)該功能,此外,該函數(shù)還可以為多個(gè)圖形創(chuàng)建統(tǒng)一的圖例。
下面將介紹如何使用 ggpubr, cowplotgridExtra包在同一頁(yè)面和多個(gè)頁(yè)面上排列多個(gè)圖形以及如何輸出圖形到文件中。

ggpubr包的安裝可以參考這篇文章-->>ggpubr:快速繪制用于發(fā)表的圖形

加載數(shù)據(jù)

數(shù)據(jù):ToothGrowth 和mtcars數(shù)據(jù)集。

# ToothGrowth
data("ToothGrowth")
head(ToothGrowth)

##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5
# mtcars 
data("mtcars")
mtcars$name <- rownames(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)
head(mtcars[, c("name", "wt", "mpg", "cyl")])

##                                name   wt  mpg cyl
## Mazda RX4                 Mazda RX4 2.62 21.0   6
## Mazda RX4 Wag         Mazda RX4 Wag 2.88 21.0   6
## Datsun 710               Datsun 710 2.32 22.8   4
## Hornet 4 Drive       Hornet 4 Drive 3.21 21.4   6
## Hornet Sportabout Hornet Sportabout 3.44 18.7   8
## Valiant                     Valiant 3.46 18.1   6

繪制圖形

繪制4個(gè)不同的圖形:

  • 使用ToothGrowth 數(shù)據(jù)集繪制一個(gè)箱線圖和點(diǎn)圖;
  • 使用mtcars數(shù)據(jù)集繪制一個(gè)條形圖和散點(diǎn)圖;

繪制箱線圖和點(diǎn)圖:

# Box plot (bp)
bxp <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                 color = "dose", palette = "jco")
bxp
# Dot plot (dp)
dp <- ggdotplot(ToothGrowth, x = "dose", y = "len",
                 color = "dose", palette = "jco", binwidth = 1)
dp

繪制條形圖和散點(diǎn)圖:

# Bar plot (bp)
bp <- ggbarplot(mtcars, x = "name", y = "mpg",
          fill = "cyl",               # 根據(jù)cyl類型填充顏色
          color = "white",            # 將條形邊框顏色設(shè)為白色
          palette = "jco",            # jco 調(diào)色板
          sort.val = "asc",           # 按升序排序
          sort.by.groups = TRUE,      # 分組排序
          x.text.angle = 90           # 垂直旋轉(zhuǎn)x軸文本
          )
bp + font("x.text", size = 8)
# Scatter plots (sp)
sp <- ggscatter(mtcars, x = "wt", y = "mpg",
                add = "reg.line",               # 添加回歸線
                conf.int = TRUE,                # 添加置信區(qū)間
                color = "cyl", palette = "jco", # 根據(jù)cyl填充顏色
                shape = "cyl"                   # 根據(jù)cyl類型設(shè)置點(diǎn)形狀
                )+
  stat_cor(aes(color = cyl), label.x = 3)       # 添加相關(guān)系數(shù)
sp

排版多個(gè)圖形

使用ggpubr包中的ggarrange()函數(shù)來排版多個(gè)圖形:

ggarrange(bxp, dp, bp + rremove("x.text"), 
          labels = c("A", "B", "C"),
          ncol = 2, nrow = 2)

或者,也可以使用cowplot包中的plot_grid()函數(shù):

library("cowplot")
plot_grid(bxp, dp, bp + rremove("x.text"), 
          labels = c("A", "B", "C"),
          ncol = 2, nrow = 2)

或者,也可以使用gridExtra包中的grid.arrange() 函數(shù):

library("gridExtra")
grid.arrange(bxp, dp, bp + rremove("x.text"), 
             ncol = 2, nrow = 2)

注釋排版的圖形

使用 annotate_figure()函數(shù):

figure <- ggarrange(sp, bp + font("x.text", size = 10),
                    ncol = 1, nrow = 2)
annotate_figure(figure,
                top = text_grob("Visualizing mpg", color = "red", face = "bold", size = 14),
                bottom = text_grob("Data source: \n mtcars data set", color = "blue",
                                   hjust = 1, x = 1, face = "italic", size = 10),
                left = text_grob("Figure arranged using ggpubr", color = "green", rot = 90),
                right = "I'm done, thanks :-)!",
                fig.lab = "Figure 1", fig.lab.face = "bold"
                )

對(duì)齊繪圖區(qū)

例如,當(dāng)需要將風(fēng)險(xiǎn)表放在生存曲線下方時(shí),便需要將兩個(gè)圖形的繪圖區(qū)對(duì)齊。

# 擬合生存曲線
install.packages("survminer")
library(survival)
fit <- survfit( Surv(time, status) ~ adhere, data = colon )
# 繪制生存曲線
library(survminer)
ggsurv <- ggsurvplot(fit, data = colon, 
                     palette = "jco",                              # jco palette
                     pval = TRUE, pval.coord = c(500, 0.4),        # Add p-value
                     risk.table = TRUE                            # Add risk table
                     )
names(ggsurv)

ggsurv 是一個(gè)包含以下兩個(gè)部分的列表:

  • plot:生存曲線
  • table:風(fēng)險(xiǎn)表圖

繪制生存曲線和風(fēng)險(xiǎn)表:

ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 1),
          ncol = 1, nrow = 2)

對(duì)齊縱坐標(biāo)軸:

ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 1),
          ncol = 1, nrow = 2, align = "v")

更改圖形的行列跨度

使用ggpubr包

使用嵌套的ggarrange() 函數(shù):

ggarrange(sp,                                                 # 第一行為散點(diǎn)圖
          ggarrange(bxp, dp, ncol = 2, labels = c("B", "C")), # 第二行為箱線圖和點(diǎn)圖
          nrow = 2, 
          labels = "A"                                        # 散點(diǎn)圖的標(biāo)簽
          ) 

使用cowplot包

使用函數(shù)ggdraw() + draw_plot() + draw_plot_label()可以將圖形放置在特定位置。
ggdraw()函數(shù)創(chuàng)建一個(gè)空畫布:

ggdraw()

畫布中的坐標(biāo)位置:

畫布中的坐標(biāo)位置

draw_plot(),將圖形放置在畫布的某個(gè)位置:

draw_plot(plot, x = 0, y = 0, width = 1, height = 1)
  • plot:ggplot2圖形或gtable
  • x, y: 圖形要放置的位置
  • width, height: 圖形的寬度和高度

draw_plot_label(),在圖的左上角添加圖標(biāo)簽:

draw_plot_label(label, x = 0, y = 1, size = 16, ...)
  • label: 要繪制的標(biāo)簽向量
  • x, y: 標(biāo)簽的位置
  • size: 標(biāo)簽字體大小

排版多個(gè)圖形:

library("cowplot")
ggdraw() +
  draw_plot(bxp, x = 0, y = .5, width = .5, height = .5) +
  draw_plot(dp, x = .5, y = .5, width = .5, height = .5) +
  draw_plot(bp, x = 0, y = 0, width = 1, height = 0.5) +
  draw_plot_label(label = c("A", "B", "C"), size = 15,
                  x = c(0, 0.5, 0), y = c(1, 1, 0.5))

使用gridExtra 包

使用arrangeGrop()函數(shù)可以修改圖形的行列跨度:

library("gridExtra")
grid.arrange(sp,                             # 第一行為跨兩列的圖形
             arrangeGrob(bxp, dp, ncol = 2), # 第二行為兩個(gè)圖形
             nrow = 2)                       # 行數(shù)


也可以使用函數(shù)grid.arrange()中的參數(shù)layout_matrix來創(chuàng)建復(fù)雜的布局:

grid.arrange(bp,                                    # 跨兩列的圖形
             bxp, sp,                               # 箱線圖和散點(diǎn)圖
             ncol = 2, nrow = 2, 
             layout_matrix = rbind(c(1,1), c(2,3)))


使用cowplot包中的draw_plot_label()函數(shù)注釋圖形:

library("gridExtra")
library("cowplot")
# 排版圖形
# 生成 gtable (gt)
gt <- arrangeGrob(bp,                               # 跨兩列的條形圖
             bxp, sp,                               # 箱線圖和散點(diǎn)圖
             ncol = 2, nrow = 2, 
             layout_matrix = rbind(c(1,1), c(2,3)))
# Add labels to the arranged plots
p <- as_ggplot(gt) +                                # 將gt轉(zhuǎn)換為ggplot
  draw_plot_label(label = c("A", "B", "C"), size = 15,
                  x = c(0, 0, 0.5), y = c(1, 0.5, 0.5)) # 添加標(biāo)簽
p

函數(shù)arrangeGrob()grid.arrange()的主要區(qū)別在于grid.arrange()會(huì)自動(dòng)輸出排版好的圖形。如果要對(duì)圖形進(jìn)行注釋,最好使用arrangeGrob()

使用grid 包

可以使用grid 包中的grid.layout()函數(shù)來創(chuàng)建復(fù)雜的布局。另外,它還提供了函數(shù)viewport()來定義布局上的區(qū)域或視圖。函數(shù)print()用于將圖放置在指定區(qū)域中。
一般步驟如下:

  1. 繪制圖形:p1, p2, p3, ...
  2. 使用grid.newpage()函數(shù)移至網(wǎng)格布局上的新頁(yè)面
  3. 創(chuàng)建一個(gè)2 x 2的布局
  4. 定義網(wǎng)格視圖
  5. 將圖形輸出到視圖上
library(grid)
# 轉(zhuǎn)移至新頁(yè)面
grid.newpage()
# 創(chuàng)建3行2列的布局
pushViewport(viewport(layout = grid.layout(nrow = 3, ncol = 2)))
# 用于在布局上定義區(qū)域的幫助函數(shù)
define_region <- function(row, col){
  viewport(layout.pos.row = row, layout.pos.col = col)
} 
# 排版圖形
print(sp, vp = define_region(row = 1, col = 1:2))   # 跨兩列
print(bxp, vp = define_region(row = 2, col = 1))
print(dp, vp = define_region(row = 2, col = 2))
print(bp + rremove("x.text"), vp = define_region(row = 3, col = 1:2))

通用圖例

要將通用圖例放在組合圖的邊緣,可以將ggarrange()函數(shù)與以下參數(shù)一起使用:

  • common.legend = TRUE: 將通用圖例放在頁(yè)邊
  • legend: 指定圖例位置
ggarrange(bxp, dp, labels = c("A", "B"),
          common.legend = TRUE, legend = "bottom")

具有邊際密度圖的散點(diǎn)圖

# 根據(jù) "Species"類型著色的散點(diǎn)圖
sp <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",
                color = "Species", palette = "jco",
                size = 3, alpha = 0.6)+
  border()                                         
# 繪制x和y的邊際密度圖
xplot <- ggdensity(iris, "Sepal.Length", fill = "Species",
                   palette = "jco")
yplot <- ggdensity(iris, "Sepal.Width", fill = "Species", 
                   palette = "jco")+
  rotate()
# 對(duì)邊際密度圖使用clean主題
yplot <- yplot + clean_theme() 
xplot <- xplot + clean_theme()
# 圖形排版
ggarrange(xplot, NULL, sp, yplot, 
          ncol = 2, nrow = 2,  align = "hv", 
          widths = c(2, 1), heights = c(1, 2),
          common.legend = TRUE)

混排表格,文字和圖形

下面將展示如何使用iris 數(shù)據(jù)集在圖表旁邊添加文本和表格。
首先繪制下面幾個(gè)圖形:

  1. 變量“ Sepal.Length”的密度圖。R函數(shù):ggdensity()
  2. Sepal.Length變量的統(tǒng)計(jì)表。R函數(shù):desc_statby()ggtexttable()
  3. 文本。R函數(shù):ggparagraph()

最后使用ggarrange()函數(shù)進(jìn)行排版。

# Density plot of "Sepal.Length"
density.p <- ggdensity(iris, x = "Sepal.Length", 
                       fill = "Species", palette = "jco")
# Draw the summary table of Sepal.Length
# Compute descriptive statistics by groups
stable <- desc_statby(iris, measure.var = "Sepal.Length",
                      grps = "Species")
stable <- stable[, c("Species", "length", "mean", "sd")]
# Summary table plot, medium orange theme
stable.p <- ggtexttable(stable, rows = NULL, 
                        theme = ttheme("mOrange"))
# Draw text
text <- paste("iris data set gives the measurements in cm",
              "of the variables sepal length and width",
              "and petal length and width, respectively,",
              "for 50 flowers from each of 3 species of iris.",
             "The species are Iris setosa, versicolor, and virginica.", sep = " ")
text.p <- ggparagraph(text = text, face = "italic", size = 11, color = "black")
# Arrange the plots on the same page
ggarrange(density.p, stable.p, text.p, 
          ncol = 1, nrow = 3,
          heights = c(1, 0.5, 0.3))

在ggplot圖中插入圖形元素

ggplot2中的annotation_custom()函數(shù)可用于在ggplot的繪圖區(qū)域內(nèi)添加表,圖形或其他基于網(wǎng)格的元素。其基本格式為:

annotation_custom(grob, xmin, xmax, ymin, ymax)
  • grob: 要插入的外部圖形元素
  • xmin, xmax : 數(shù)據(jù)坐標(biāo)中的水平位置
  • ymin, ymax : 數(shù)據(jù)坐標(biāo)中的垂直位置

將表格插入ggplot圖中

density.p + annotation_custom(ggplotGrob(stable.p),
                              xmin = 5.5, ymin = 0.7,
                              xmax = 8)

將箱線圖插入ggplot圖中

# Scatter plot colored by groups ("Species")
sp <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",
                color = "Species", palette = "jco",
                size = 3, alpha = 0.6)
# Create box plots of x/y variables
# Box plot of the x variable
xbp <- ggboxplot(iris$Sepal.Length, width = 0.3, fill = "lightgray") +
  rotate() +
  theme_transparent()
# Box plot of the y variable
ybp <- ggboxplot(iris$Sepal.Width, width = 0.3, fill = "lightgray") +
  theme_transparent()
# Create the external graphical objects
# called a "grop" in Grid terminology
xbp_grob <- ggplotGrob(xbp)
ybp_grob <- ggplotGrob(ybp)
# Place box plots inside the scatter plot
xmin <- min(iris$Sepal.Length); xmax <- max(iris$Sepal.Length)
ymin <- min(iris$Sepal.Width); ymax <- max(iris$Sepal.Width)
yoffset <- (1/15)*ymax; xoffset <- (1/15)*xmax
# Insert xbp_grob inside the scatter plot
sp + annotation_custom(grob = xbp_grob, xmin = xmin, xmax = xmax, 
                       ymin = ymin-yoffset, ymax = ymin+yoffset) +
  # Insert ybp_grob inside the scatter plot
  annotation_custom(grob = ybp_grob,
                       xmin = xmin-xoffset, xmax = xmin+xoffset, 
                       ymin = ymin, ymax = ymax)

將背景圖插入ggplot圖中

導(dǎo)入背景圖。根據(jù)背景圖的格式,可以使用jpeg 包中的函數(shù)readJPEG()或png包中的函數(shù)readPNG()

# 導(dǎo)入背景圖
install.packages("png")
library(png)
img.file <- download.file("http://www.sthda.com/english/sthda-upload/images/ggpubr/ggpubr.png", destfile ="ggpubr.png", mode = 'wb')
img <- png::readPNG('ggpubr.png')

將ggplot與背景圖合并:

library(ggplot2)
library(ggpubr)
ggplot(iris, aes(Species, Sepal.Length))+
  background_image(img)+
  geom_boxplot(aes(fill = Species), color = "white")+
  fill_palette("jco")

使用alpha參數(shù)修改箱線圖的透明度:

library(ggplot2)
library(ggpubr)
ggplot(iris, aes(Species, Sepal.Length))+
  background_image(img)+
  geom_boxplot(aes(fill = Species), color = "white", alpha = 0.5)+
  fill_palette("jco")

將法國(guó)地圖作為另一個(gè)圖形的背景圖:

mypngfile <- download.file("https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/France_Flag_Map.svg/612px-France_Flag_Map.svg.png", 
                           destfile = "france.png", mode = 'wb') 
img <- png::readPNG('france.png') 
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  background_image(img)+
  geom_point(aes(color = Species), alpha = 0.6, size = 5)+
  color_palette("jco")+
  theme(legend.position = "top")

多頁(yè)圖形的排版

如果圖形數(shù)量很多,就需要將其放置在多個(gè)頁(yè)面上了,而ggarrange()函數(shù)便可以實(shí)現(xiàn)這種功能。當(dāng)指定了nrowncol之后,ggarrange()函數(shù)便可以自動(dòng)計(jì)算排版所有圖形所需的頁(yè)數(shù)。

# 兩頁(yè)的列表,每頁(yè)兩個(gè)圖
multi.page <- ggarrange(bxp, dp, bp, sp,
                        nrow = 1, ncol = 2)
# 查看每個(gè)頁(yè)面
multi.page[[1]] 
multi.page[[2]] 

也可以使用ggexport()函數(shù)到處為文件:

ggexport(multi.page, filename = "multi.page.ggplot2.pdf")

PDF file: multi.page.ggplot2.pdf
也可以使用marrangeGrob()函數(shù)實(shí)現(xiàn)多頁(yè)輸出。

library(gridExtra)
res <- marrangeGrob(list(bxp, dp, bp, sp), nrow = 1, ncol = 2)
# 輸出為pdf文件
ggexport(res, filename = "multi.page.ggplot2.pdf")
res

使用ggarrange()的嵌套布局

p1 <- ggarrange(sp, bp + font("x.text", size = 9),
                ncol = 1, nrow = 2)
p2 <- ggarrange(density.p, stable.p, text.p, 
                ncol = 1, nrow = 3,
                heights = c(1, 0.5, 0.3))
ggarrange(p1, p2, ncol = 2, nrow = 1)

導(dǎo)出圖形

使用函數(shù)ggexport()。
首先繪制四個(gè)圖形:

plots <- ggboxplot(iris, x = "Species",
                   y = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"),
                   color = "Species", palette = "jco"
                   )
plots[[1]]  
plots[[2]] 

然后,可以將單個(gè)圖形導(dǎo)出到文件(pdf,eps或png),導(dǎo)出時(shí)還可以進(jìn)行排版。
將單個(gè)圖導(dǎo)出到pdf文件(每頁(yè)一個(gè)圖):

ggexport(plotlist = plots, filename = "test.pdf")

排版并導(dǎo)出:

ggexport(plotlist = plots, filename = "test.pdf",
         nrow = 2, ncol = 1)

參考

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容