R语言 并排绘制多张ggplot2图

R语言 并排绘制多张ggplot2图

在R编程语言中,我们可以通过创建不同的图形或情节来分析数据。有时为了进行分析,我们需要同时看到两个或多个并排的图。在这种情况下,我们使用R语言的 gridExtra 包,它将框架划分为网格,你可以在这些网格中添加多个图。

gridExtra包含一个叫做arrange()的函数,用来根据需要排列图。

语法

grid.arrange(plot1, plot2, …, plotn, ncol, nrow)

参数

  • plot:一些情节
  • ncol:列的数量
  • nrow:行的数量

要开始做这个,首先要为所有的绘图创建数据。然后,导入必要的软件包,以帮助满足要求。需要安装和导入的一个最重要的包是gridExtra,因为没有这个包,图就不会被安排在所需的框架中。

现在创建并存储所有创建的数据的图。一旦这些图准备好了,就用arrange()函数用所需的参数来排列它们。

例1 :

# Create sample data
set.seed(5642)                             
sample_data1<- round(rnorm(100, 10, 5))         
sample_data2 <- data.frame(x = rnorm(1000),        
                    y = rnorm(1000))
  
# Load ggplot2 and gridExtra
library("ggplot2") 
library("gridExtra")
  
# Create both plot and store in variable
plot1<-ggplot(data.frame(sample_data1), aes(sample_data1)) + 
geom_histogram(bins = 10, fill="#04c24a", color="gray")
  
plot2<- ggplot(sample_data2, aes(x = x, y = y)) + geom_point(color="#04c24a")
  
# Divide frame in grid using grid.arrange function 
# and put above created plot int it
grid.arrange(plot1, plot2, ncol = 2)

输出

并排绘制多张ggplot2图

例2 :

# Create sample data
set.seed(5642)                             
sample_data1 <- data.frame(name=c("Geek1","Geek2","Geek3",
                                  "Geek4","Geeek5") ,
                           value=c(31,12,15,28,45)) 
  
sample_data2 <- data.frame(x = rnorm(400))
sample_data3 <- data.frame(name=c("C++","C#","Java","R","Pyhton") ,
                           value=c(301,112,115,228,145))
  
# Load ggplot2 and gridExtra
library("ggplot2") 
library("gridExtra")
  
# Create both plot and store in variable
plot1<-ggplot(sample_data1, aes(x=name, y=value))+
geom_segment( aes(x=name, xend=name, y=0, yend=value), color="grey") +
geom_point( color="green", size=4)
  
plot2<-ggplot(sample_data2, aes(x = x)) + 
geom_density(fill="#69b3a2", color="#e9ecef", alpha=0.8)
  
plot3<-ggplot(sample_data3, aes(x=name, y=value)) + 
geom_bar(fill="#69b3a2", stat = "identity")
  
# Divide frame in grid using grid.arrange function 
# and put above created plot int it
grid.arrange(plot1, plot2,plot3, ncol= 3)

输出

并排绘制多张ggplot2图

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程