推荐一个用来拼图的包:patchwork
.作者是Thomas Lin Pedersen.使用方法非常简洁,具体使用方法可以查看其帮助文档.他的思想跟tidyverse
非常像,直接使用+
,-
等符号来进行图的拼接.举个例子说明.
1 安装
patchwork
devtools::install_github("thomasp85/patchwork")
2 使用
拼图有两种不同的含义:
像一幅图中不同的panel一样,他们分别是独立的;
反映同样的数据信息,将几个图拼成一个panel.比如对于一个散点图,在其右侧和左侧分别添加其对应的变量的密度分布图等.
library(patchwork)
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 3.6.1
## -- Attaching packages -------------------------------------------------------------------------------------------- tidyverse 1.2.1 --
## v ggplot2 3.2.1 v purrr 0.3.2
## v tibble 2.1.3 v dplyr 0.8.3
## v tidyr 1.0.0 v stringr 1.4.0
## v readr 1.3.1 v forcats 0.4.0
## Warning: package 'ggplot2' was built under R version 3.6.1
## Warning: package 'tibble' was built under R version 3.6.1
## Warning: package 'tidyr' was built under R version 3.6.1
## Warning: package 'dplyr' was built under R version 3.6.1
## -- Conflicts ----------------------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
plot1 <-
ggplot(mtcars, aes(x = mpg, y = disp)) +
geom_point() +
theme_bw() +
scale_x_continuous(limits = c(10, 35)) +
scale_y_continuous(limits = c(50, 500))
plot2 <-
ggplot(mtcars, aes(x = mpg)) +
geom_histogram() +
theme_bw() +
scale_x_continuous(limits = c(10, 35),
name = NULL, labels = NULL, breaks = NULL) +
scale_y_continuous(expand = expand_scale(mult = c(0, .05))) +
theme(panel.border = element_blank(),
axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
plot3 <-
ggplot(mtcars, aes(x = disp)) +
geom_histogram() +
theme_bw() +
coord_flip() +
scale_x_continuous(limits = c(150, 500),
name = NULL, labels = NULL, breaks = NULL) +
scale_y_continuous(expand = expand_scale(mult = c(0, .05))) +
theme(panel.border = element_blank(),
axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
我们画出了汽车mpg
和disp
的关系,然后想在这个散点图上方和右方分别画上disp
和mpg
的分布图.这时候需要注意的是,需要确定xlim
和ylim
的发明,从而使其坐标轴能够精确对上.
plot <-
{plot2 + plot_spacer() + plot_layout(ncol = 2, widths = c(3, 1))} -
{plot1 + plot3 + plot_layout(ncol = 2, widths = c(3, 1))} +
plot_layout(ncol = 1, heights = c(1,3))
plot
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 2 rows containing missing values (geom_bar).
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 12 rows containing non-finite values (stat_bin).
## Warning: Removed 2 rows containing missing values (geom_bar).
plot_spacer()
函数用来生成一个空白图片.plot_layout()
函数用来设置拼接图片的一些具体参数,如列数,行数,宽度或者高度比等.
{}
括起来的几个plot组成一个完整的新的plot.
这里面需要注意的是-
.它是指该符号左右两侧当成两个新的图层进行拼接.
具体使用方法可以参考作者github(https://github.com/thomasp85/patchwork).