在 R 中组合多个 ggplot2 图例
在本文中,我们将看到如何在 R 编程语言中组合多个 ggplot2 Legends。
安装
首先,使用library()函数加载 ggplot2 包。如果您还没有安装它,您可以通过在 R 控制台中编写以下命令来简单地安装它。
install.packages("ggplot2")
要创建 R 图,我们使用ggplot()函数,为了使其成为散点图,我们将geom_point()函数添加到 ggplot()函数。让我们首先在同一个图中创建一个包含多个图例的图而不合并,以便差异明显。
例子:
R
# Load Package
library("ggplot2")
# Create a DataFrame
data <- data.frame(Xdata = rnorm(6),
Ydata = rnorm(6),
Group1 = c("ld-01", "ld-02", "ld-03",
"ld-04", "ld-05", "ld-06"),
Group2 = c("ld-01", "ld-02", "ld-03",
"ld-04", "ld-05", "ld-06"))
# Create a Scatter Plot With Multiple Legends
ggplot(data, aes(Xdata, Ydata, color = Group1, shape = Group2)) +
geom_point(size = 7)
R
# Load Package
library("ggplot2")
# Create a DataFrame
data <- data.frame(Xdata = rnorm(6),
Ydata = rnorm(6),
Group1 = c("ld-01", "ld-02", "ld-03",
"ld-04", "ld-05", "ld-06"),
Group2 = c("ld-01", "ld-02", "ld-03",
"ld-04", "ld-05", "ld-06"))
# Create a Scatter Plot with Combined
# multiple legends
ggplot(data, aes(Xdata, Ydata, color = Group2, shape = Group2)) +
geom_point(size = 7)
输出:
正如您在上图中所看到的,两个图例 Group1 代表颜色,Group2 代表散点图中点的形状,它们的轮廓不同。要将它们组合成一个图例,我们应该只从两个图例中选择一个。这里我们选择了 Group2,因此我们将 Group2 分配给 aes()函数的颜色和形状参数。您也可以选择 Group1。
例子:
电阻
# Load Package
library("ggplot2")
# Create a DataFrame
data <- data.frame(Xdata = rnorm(6),
Ydata = rnorm(6),
Group1 = c("ld-01", "ld-02", "ld-03",
"ld-04", "ld-05", "ld-06"),
Group2 = c("ld-01", "ld-02", "ld-03",
"ld-04", "ld-05", "ld-06"))
# Create a Scatter Plot with Combined
# multiple legends
ggplot(data, aes(Xdata, Ydata, color = Group2, shape = Group2)) +
geom_point(size = 7)
输出: