R语言 如何合并多个ggplot2图

R语言 如何合并多个ggplot2图

在这篇文章中,我们将讨论如何在R编程语言中合并多个ggplot2图。

使用 “+”号 组合多个ggplot2 图,并将其添加 到最终图中

在这种合并多个绘图的方法中,用户可以在一个绘图中添加不同类型的绘图或不同数据的绘图,用户只需要使用’+’号将每个绘图合并到最后的绘图中,进一步说,最后的绘图将是R编程语言中单个ggplot2绘图的多个绘图的组合。

语法:

ggplot(NULL, aes(x, y)) +geom_line(数据1)+geom_line(数据2)+……+geom_line(数据n)

例1 :

在这个例子中,我们将使用’+’号的形式将3个不同数据的ggplot2线图组合成R编程语言中的一个图。

# load the package
library("ggplot2")
  
# create dataframe
gfg1 < -data.frame(x=c(4, 5, 1, 7, 8), 
                   y=c(1, 4, 8, 6, 9))
  
# create dataframe
gfg2 < -data.frame(x=c(5, 1, 4, 3, 7),
                   y=c(7, 8, 9, 1, 2))
  
# create dataframe
gfg3 < -data.frame(x=c(4, 8, 6, 3, 5),
                   y=c(3, 4, 5, 8, 7))
  
# plot the data with dataframes with green
# red and blue colors
gfg_plot < -ggplot(NULL, aes(x, y)) + 
geom_line(data=gfg1, col="green") +
geom_line(data=gfg2, col="blue")+
geom_line(data=gfg3, col="red")
  
# display the plot
gfg_plot

输出

如何在R语言中合并多个ggplot2图?

例2 :

在这个例子中,我们将结合3个ggplot2线图和2个散点ggplot2图,总共5个不同数据的图,使用’+’号形式在R编程语言中结合成一个图。

# load the package
library("ggplot2")
  
# create 5 dataframes
gfg1 < -data.frame(x=c(4, 5, 1, 7, 8), 
                   y=c(1, 4, 8, 6, 9))
gfg2 < -data.frame(x=c(5, 1, 4, 3, 7),
                   y=c(7, 8, 9, 1, 2))
gfg3 < -data.frame(x=c(4, 8, 6, 3, 5), 
                   y=c(3, 4, 5, 8, 7))
gfg4 < -data.frame(x=c(8, 6, 7, 2, 1), 
                   y=c(8, 6, 4, 1, 9))
gfg5 < -data.frame(x=c(6, 1, 6, 5, 4),
                   y=c(6, 8, 7, 6, 4))
  
# plot the data with 5 dataframes
# with 5 different colors
gfg_plot < -ggplot(NULL, aes(x, y)) + 
geom_line(data=gfg1, col="green") +
geom_line(data=gfg2, col="blue")+
geom_line(data=gfg3, col="red")+
geom_point(data=gfg4, col="purple") + 
geom_point(data=gfg5, col="black")
  
# display the plot
gfg_plot

输出

如何在R语言中合并多个ggplot2图?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程