在R中组合来自不同DataFrame的两个ggplot2图
在本文中,我们将学习如何在 R 编程语言中组合来自不同 DataFrame 的两个 ggplot2 图。在本文中,我们使用散点图,但它可以应用于任何其他图。
让我们首先通过不同的数据帧单独绘制两个 ggplot2 散点图,然后我们将看到如何将它们组合在一起,即如何在一个绘图字段中绘制两个图。
情节 1:
R
# Load Packages
library("ggplot2")
# DataFrame for first Scatterplot
pointDF1 <- data.frame(XDF1 = rnorm(50),
YDF1 = rnorm(50))
# Create First Plot using ggplot2
ggplot(pointDF1, aes(XDF1, YDF1)) +
geom_point(fill = "dark green", color = "black",
size = 5, shape = 21)+
ggtitle("Plot-1")
R
# Load Packages
library("ggplot2")
# DataFrame for second Scatterplot
pointDF2 <- data.frame(XDF2 = rnorm(50),
YDF2 = rnorm(50))
# Create Second Plot using ggplot2
ggplot(pointDF2, aes(XDF2, YDF2)) +
geom_point(fill = "green", color = "black",
size = 5, shape = 21)+
ggtitle("Plot-2")
R
# Load Packages
library("ggplot2")
# DataFrame for first Scatterplot
pointDF1 <- data.frame(XDF1 = rnorm(50),
YDF1 = rnorm(50))
# DataFrame for second Scatterplot
pointDF2 <- data.frame(XDF2 = rnorm(50),
YDF2 = rnorm(50))
# Combine Two Plots of different
# DataFrames using ggplot2
ggplot() +
geom_point(data = pointDF1, aes(XDF1,YDF1),
fill = "dark green", color = "black",
size = 5, shape = 21)+
geom_point(data = pointDF2, aes(XDF2,YDF2),
fill = "green", color = "black",
size = 5, shape = 21)+
labs(x = "X-Data", y = "Y-Data")+
ggtitle("Combined Plot")
输出:
情节 2:
电阻
# Load Packages
library("ggplot2")
# DataFrame for second Scatterplot
pointDF2 <- data.frame(XDF2 = rnorm(50),
YDF2 = rnorm(50))
# Create Second Plot using ggplot2
ggplot(pointDF2, aes(XDF2, YDF2)) +
geom_point(fill = "green", color = "black",
size = 5, shape = 21)+
ggtitle("Plot-2")
输出:
现在我们要把上面的图组合成一个图。除了绘图部分,一切正常。组合该函数以在一帧中绘制两个图。
合并这两个图后,出现了应该使用什么轴标签的问题。答案是 labs()函数可用于提供自定义标签。这一步是完全可选的。
句法:
labs(x = “X-Label”, y = “Y-label”)
例子:
电阻
# Load Packages
library("ggplot2")
# DataFrame for first Scatterplot
pointDF1 <- data.frame(XDF1 = rnorm(50),
YDF1 = rnorm(50))
# DataFrame for second Scatterplot
pointDF2 <- data.frame(XDF2 = rnorm(50),
YDF2 = rnorm(50))
# Combine Two Plots of different
# DataFrames using ggplot2
ggplot() +
geom_point(data = pointDF1, aes(XDF1,YDF1),
fill = "dark green", color = "black",
size = 5, shape = 21)+
geom_point(data = pointDF2, aes(XDF2,YDF2),
fill = "green", color = "black",
size = 5, shape = 21)+
labs(x = "X-Data", y = "Y-Data")+
ggtitle("Combined Plot")
输出: