Skip to main content
 首页 » 编程设计

R语言ggplot2画组合图

2022年07月19日12198°冷暖

我们通常会希望使用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)) 
) 

在这里插入图片描述


本文参考链接:https://blog.csdn.net/neweastsun/article/details/122014446
阅读延展