安装所需要的R包
BiocManager::install("patchwork")
BiocManager::install("cowplot")
加载所需的R包,并将默认主题设置为theme_bw(),并将图例放在图的顶部
library(ggplot2)
library(cowplot)
library(patchwork)
theme_set(
theme_bw() +
theme(legend.position = "top")
)
创建一些基本图像:
library("ggplot2")
my3cols <- c("#E7B800", "#2E9FDF", "#FC4E07")
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x = dose, y = len))
bxp <- p + geom_boxplot(aes(color = dose)) +
scale_color_manual(values = my3cols)
dp <- p + geom_dotplot(aes(color = dose, fill = dose),
binaxis='y', stackdir='center') +
scale_color_manual(values = my3cols) +
scale_fill_manual(values = my3cols)
lp <- ggplot(economics, aes(x = date, y = psavert)) +
geom_line(color = "#E46726")
dens <- ggplot(iris, aes(Sepal.Length)) +
geom_density(aes(color = Species)) +
scale_color_manual(values = my3cols)
patchwork包水平拼接
bxp + dens
bxp | dens
1.png
垂直布局
可以通过向plot_layout()来指定布局,可以定义网格的尺寸以及要分配给不同行和列的空间
bxp + dens + plot_layout(ncol = 1)
2.png
指定每个图的尺寸
bxp + dens + plot_layout(ncol = 1, heights = c(1, 3))
bxp + dens + plot_layout(ncol = 2, width = c(1, 2))
3.png
4.png
增加图片之间的空间
bxp + plot_spacer() + dens
5.png
嵌套布局
您可以通过将部分图用括号括起来来制作嵌套图版面
lp + {
dens + {
bxp +
dp +
plot_layout(ncol = 1)
}
} +
plot_layout(ncol = 1)
6.png
高级功能
bxp + dp - lp + plot_layout(ncol = 1)
7.png
patchwork同时提供|和/分别用于水平和垂直布局
(bxp | lp | dp) / dens
8.png
可以使用&或向所有子图添加元素,而不必单独修改所有图。两者的不同之处仅在于将影响当前嵌套级别上的图:
(bxp + (dp + dens) + lp + plot_layout(ncol = 1)) * theme_gray()
9.png
而&将递归到嵌套级别:
(bxp + (dp + dens) + lp + plot_layout(ncol = 1)) & theme_gray()
10.png
添加标记
patchwork <- (bxp + (dp + dens) +
lp + plot_layout(ncol = 1)) & theme_gray()
patchwork + plot_annotation(tag_levels = 'A')
11.png
library("cowplot")
plot_grid(bxp, dp, dens ,
labels = c("A", "B", "C"),
ncol = 2, nrow = 2)
12.png
网友评论