R语言基础画图使用函数par()以及layout()将多个图形组合在同一幅图中,但是这两个函数不适用于ggplot2和ggpubr,ggplot2和ggpubr作图如果希望把多张图放到同一个页面上,基本解决方案是使用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)
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)
library(gridExtra)
grid.arrange(bxp, dp, bp+rremove("x.text"),
ncol = 2, nrow = 2)
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"
)
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)
- 对齐
ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 0.7),
ncol = 1, nrow = 2, align = "v")
5. 更改图的列/行跨度
5.1 使用ggpubr包
ggarrange(sp, # 第一行散点图
ggarrange(bxp, dp, ncol = 2, labels = c("B", "C")), # 第二行箱形图和点图
nrow = 2,
labels = "A" # 散点图的标签
)
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()
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))
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
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)))
为了轻松注释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
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))
6.将通用图例用于组合ggplots
ggarrange(bxp, dp, labels = c("A", "B"),
common.legend = TRUE, legend = "bottom")
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)
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))
9.在ggplot中插入图形元素
density.p + annotation_custom(ggplotGrob(stable.p),
xmin = 5.5, ymin = 0.7,
xmax = 8)
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)
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")
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")
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)
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/