ggplot2画组合图

我们通常会希望使用ggplot2创建横向、纵向并列图,方便同时对比查看数据的不同方面特性。我们可以使用patchwork包很容易实现。

加载包


#install ggplot2 and patchwork packages
install.packages('ggplot2')
install.packages('patchwork')

#load the packages 
library(ggplot2)
library(patchwork)

本文我们展示几个示例教你使用这些包创建多个并列图。

两个并列图

下面代码展示如何创建两个并列图,使用R内置的iris数据集:

#create box plot
plot1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot()

#create density plot
plot2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
  geom_density(alpha = 0.8)

#display plots side by side
plot1 + plot2 

在这里插入图片描述

三个并列图

下面代码展示如何创建三个并列图:

#create box plot
plot1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot()

#create density plot
plot2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
  geom_density(alpha = 0.7)

#create scatterplot 
plot3 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(colour=factor(Species), shape=factor(Species)))

#display three plots side by side
plot1 + plot2 + plot3

在这里插入图片描述

两个垂直排列图

下面代码展示如何创建两个垂直排列图:

#create box plot
plot1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot()

#create density plot
plot2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
  geom_density(alpha = 0.7)

#display plots stacked on top of each other
plot1 / plot2 

在这里插入图片描述

组合排列

下面展示上面一行一个图,下面一行并列展示两个图:

#create box plot
plot1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot()

#create density plot
plot2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
  geom_density(alpha = 0.7)

#create scatterplot 
plot3 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(colour=factor(Species), shape=factor(Species)))

#display plots stacked on top of each other
plot1 / (plot2 + plot3)

在这里插入图片描述

给组合图增加标题、子标题、题注

plot_annotation函数可以实现对组合图添加标题、子标题、题注等,下面代码展示如何实现:

#create box plot
plot1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  ggtitle('Boxplot')

#create density plot
plot2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
  geom_density(alpha = 0.7) +
  ggtitle('Density Plot')

#display plots side by side with title, subtitle, and captions
patchwork <- plot1 + plot2 

patchwork + plot_annotation(
  title = 'This is a title',
  subtitle = 'This is a subtitle that describes more information about the plots',
  caption = 'This is a caption',
  theme = theme(plot.title = element_text(size = 19))
)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值