ggplot2 009 組合圖形

R語言基礎畫圖使用函數par()以及layout()將多個圖形組合在同一幅圖中,但是這兩個函數不適用于ggplot2ggpubr,ggplot2ggpubr作圖如果希望把多張圖放到同一個頁面上,基本解決方案是使用gridExtra R軟件包。
grid.arrange()rangingGrob()在一頁上排列多個ggplots,marrangeGrob()用于在多個頁面上排列多個ggplots。但是,這些功能不會嘗試對齊打印面板; 取而代之的是,將圖簡單地按原樣放置到網格中,從而使軸不對齊。
如果需要進行軸對齊,則可以切換到Cowplot程序包,該程序包包含帶有align參數的函數plot_grid()。 但是,Cowplot程序包不包含任何用于多頁布局的解決方案。 因此,我們提供了ggarrange()函數(在ggpubr中),它是plot_grid()函數的包裝器,用于在多個頁面上排列多個ggplots。 它還可以為多個圖創建通用的唯一圖例

1.ggpubr安裝及加載

install.packages("ggpubr")
library(ggpubr)
ggarrange用法

ggarrange( ..., plotlist = NULL, ncol = NULL, nrow = NULL, labels = NULL, label.x = 0, label.y = 1, hjust = -0.5, vjust = 1.5, font.label = list(size = 14, color = "black", face = "bold", family = NULL), align = c("none", "h", "v", "hv"), widths = 1, heights = 1, legend = NULL, common.legend = FALSE, legend.grob = NULL )

2.圖形重排

2.1 創建數據及繪圖

# 首次使用需要安裝和加載以下包
install.packages("cowplot")
library(cowplot)
install.packages("ggpubr")
Library(ggpubr)
install.packages("gridExtra")
Library(gridExtra)

# 加載數據ToothGrowth
data("ToothGrowth")
# 檢查數據
head(ToothGrowth)
# 加載數據mtcars 
data("mtcars")
mtcars$name <- rownames(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)
head(mtcars[, c("name", "wt", "mpg", "cyl")])

# Box plot (bxp)
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
# Bar plot (bp)
bp <- ggbarplot(mtcars, x = "name", y = "mpg",
                fill = "cyl",               # change fill color by cyl
                color = "white",            # Set bar border colors to white
                palette = "jco",            # jco journal color palett. see ?ggpar
                sort.val = "asc",           # Sort the value in ascending order
                sort.by.groups = TRUE,      # Sort inside each group
                x.text.angle = 90           # Rotate vertically x axis texts
)
bp + font("x.text", size = 8)
# Scatter plots (sp)
sp <- ggscatter(mtcars, x = "wt", y = "mpg",
                add = "reg.line",               # Add regression line
                conf.int = TRUE,                # Add confidence interval
                color = "cyl", palette = "jco", # Color by groups "cyl"
                shape = "cyl"                   # Change point shape by groups "cyl"
)+
  stat_cor(aes(color = cyl), label.x = 3)       # Add correlation coefficient
sp

2.2 ggarrange() (in ggpubr)

# 圖形重排,圖形的排列順序取決于ggarrange圖形的排列順序
# bp + rremove("x.text"),移除圖形bp的x坐標軸標簽
ggarrange(bxp, dp, bp + rremove("x.text"), 
          labels = c("A", "B", "C"),
          ncol = 2, nrow = 2)
image.png

2.3 plot_grid() [in cowplot]

install.packages("cowplot")
library(cowplot)
plot_grid(bxp, dp, bp+rremove("x.text"), 
          labels = c("A", "B", "C"),
          ncol = 2, nrow = 2)
image.png
library(gridExtra)
grid.arrange(bxp, dp, bp+rremove("x.text"), 
             ncol = 2, nrow = 2)
image.png

3.重排圖形的注釋annotate_figure() [in ggpubr]

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

image.png

4.對齊面板Align plot panels

# Fit survival curves
install.packages("survival")
library(survival)
fit <- survfit( Surv(time, status) ~ adhere, data = colon )
# Plot survival curves
install.packages("survminer")
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)
  • 未對齊
ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 0.7),
          ncol = 1, nrow = 2)
image.png
  • 對齊
ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 0.7),
          ncol = 1, nrow = 2, align = "v")
image.png

5. 更改圖的列/行跨度

5.1 使用ggpubr包
ggarrange(sp,                                                 # 第一行散點圖
          ggarrange(bxp, dp, ncol = 2, labels = c("B", "C")), # 第二行箱形圖和點圖
          nrow = 2, 
          labels = "A"                                        # 散點圖的標簽
) 
image.png
5.2 使用cowplot包

ggdraw()+ draw_plot()+ draw_plot_label()函數的組合可用于將圖形放置在具有特定大小的特定位置。

  • ggdraw()
    ggdraw(plot = NULL, xlim = c(0, 1), ylim = c(0, 1), clip = "off")
    draw_plot(). Places a plot somewhere onto the drawing canvas:
  • draw_plot()
    draw_plot(plot, x = 0, y = 0, width = 1, height = 1, scale = 1, hjust = 0, vjust = 0)
  • draw_plot_label()
    draw_plot_label(label, x = 0, y = 1, hjust = -0.5, vjust = 1.5, size = 16, fontface = "bold", family = NULL, color = NULL, colour, ...)
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))
image.png
5.3 使用gridExtra包
library("gridExtra")
grid.arrange(sp,                             # First row with one plot spaning over 2 columns
             arrangeGrob(bxp, dp, ncol = 2), # Second row with 2 plots in 2 different columns
             nrow = 2)                       # Number of rows
image.png
grid.arrange(bp,                                    # bar plot spaning two columns
             bxp, sp,                               # box plot and scatter plot
             ncol = 2, nrow = 2, 
             layout_matrix = rbind(c(1,1), c(2,3)))
image.png

為了輕松注釋grid.arrange()/ rangeGrob()輸出(一個gtable),可以先使用函數as_ggplot()[在ggpubr中]將其轉換為ggplot。 接下來使用draw_plot_label()[在cowplot中]對其進行注釋。

library("gridExtra")
library("cowplot")
# Arrange plots using arrangeGrob
# returns a gtable (gt)
gt <- arrangeGrob(bp,                               # bar plot spaning two columns
                  bxp, sp,                               # box plot and scatter plot
                  ncol = 2, nrow = 2, 
                  layout_matrix = rbind(c(1,1), c(2,3)))
# Add labels to the arranged plots
p <- as_ggplot(gt) +                                # transform to a ggplot
  draw_plot_label(label = c("A", "B", "C"), size = 15,
                  x = c(0, 0, 0.5), y = c(1, 0.5, 0.5)) # Add labels
p
image.png
5.4 使用grid包
library(grid)
# Move to a new page
grid.newpage()
# Create layout : nrow = 3, ncol = 2
pushViewport(viewport(layout = grid.layout(nrow = 3, ncol = 2)))
# A helper function to define a region on the layout
define_region <- function(row, col){
  viewport(layout.pos.row = row, layout.pos.col = col)
} 
# Arrange the plots
print(sp, vp = define_region(row = 1, col = 1:2))   # Span over two columns
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))
image.png

6.將通用圖例用于組合ggplots

ggarrange(bxp, dp, labels = c("A", "B"),
          common.legend = TRUE, legend = "bottom")
image.png

7.具有邊際密度圖的散點圖

# Scatter plot colored by groups ("Species")
sp <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",
                color = "Species", palette = "jco",
                size = 3, alpha = 0.6)+
  border()                                         
# Marginal density plot of x (top panel) and y (right panel)
xplot <- ggdensity(iris, "Sepal.Length", fill = "Species",
                   palette = "jco")
yplot <- ggdensity(iris, "Sepal.Width", fill = "Species", 
                   palette = "jco")+
  rotate()
# Cleaning the plots
yplot <- yplot + clean_theme() 
xplot <- xplot + clean_theme()
# Arranging the plot
ggarrange(xplot, NULL, sp, yplot, 
          ncol = 2, nrow = 2,  align = "hv", 
          widths = c(2, 1), heights = c(1, 2),
          common.legend = TRUE)
image.png

8.混合表格,文字和ggplot2圖形

# 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))
image.png

9.在ggplot中插入圖形元素

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

10.將箱形圖放在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)
image.png

11.將背景圖像添加到ggplot2圖形

# Import the image
install.packages("png") 
library(png)
# 網址鏈接已失效,無法加載圖片
img.file <- system.file(file.path("http://www.sthda.com/english/sthda-upload/images/ggpubr", "background-image.png"),
                        package = "ggpubr")
img <- png::readPNG("img.file")

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

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

上述網址失效,無法加載圖片,繪圖報錯

library(ggplot2)
library(ggpubr)
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")
image.png

12.多頁排列

如果有很長的ggplots列表,例如n = 20個圖,則可能要排列這些圖并將它們放在多頁上。 每頁有4個地塊,您需要5頁才能容納20個地塊。
函數ggarrange()[在ggpubr中提供]提供了一種方便的解決方案,可以在多個頁面上排列多個ggplots。 在指定參數nrow和ncol之后,函數ggarrange()會自動計算保存繪圖列表所需的頁數。 它返回一個排列的ggplots列表。

multi.page <- ggarrange(bxp, dp, bp, sp,
                        nrow = 1, ncol = 2)
multi.page[[1]] # Visualize page 1
multi.page[[2]] # Visualize page 2
ggexport(multi.page, filename = "multi.page.ggplot2.pdf")

multi.page[[1]]

multi.page[[2]]
library(gridExtra)
res <- marrangeGrob(list(bxp, dp, bp, sp), nrow = 1, ncol = 2)
# Export to a pdf file
ggexport(res, filename = "multi.page.ggplot2.pdf")
# Visualize interactively
res

13.使用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)
image.png

14.導出圖形

R函數:ggexport() [在ggpubr中]。

plots <- ggboxplot(iris, x = "Species",
                   y = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"),
                   color = "Species", palette = "jco"
)
plots[[1]]  # Print the first plot
plots[[2]]  # Print the second plots and so on...
ggexport(plotlist = plots, filename = "test.pdf")
ggexport(plotlist = plots, filename = "test.pdf",
         nrow = 2, ncol = 1)

Reference

ggplot2 - Easy Way to Mix Multiple Graphs on The Same Page
http://www.sthda.com/english/articles/24-ggpubr-publication-ready-plots/81-ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,702評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,615評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,606評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,044評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,826評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,227評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,307評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,447評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,992評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,807評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,001評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,550評論 5 361
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,243評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,667評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,930評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,709評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,996評論 2 374