[英]How to set multiple legends / scales for the same aesthetic in ggplot2?
我正在 ggplot2 中繪制來自多個數據幀的數據,如下所示:
# subset of iris data
vdf = iris[which(iris$Species == "virginica"),]
# plot from iris and from vdf
ggplot(iris) +
geom_line(aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) +
geom_line(aes(x=Sepal.Width, y=Sepal.Length), colour="gray", size=2,
data=vdf)
colour
的圖例僅包括來自iris
的條目,而不包括來自vdf
的條目。 如何讓 ggplot2 從data=vdf
vdf 添加一個圖例,在這種情況下,它是iris
的圖例下方的一條灰線? 謝謝。
您應該將顏色設置為aes
以在圖例中顯示。
# subset of iris data
vdf = iris[which(iris$Species == "virginica"),]
# plot from iris and from vdf
library(ggplot2)
ggplot(iris) + geom_line(aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) +
geom_line(aes(x=Sepal.Width, y=Sepal.Length, colour="gray"),
size=2, data=vdf)
編輯我認為你不能為同一個 aes 擁有多個圖例。 這里的解決方法:
library(ggplot2)
ggplot(iris) +
geom_line(aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) +
geom_line(aes(x=Sepal.Width, y=Sepal.Length,size=2), colour="gray", data=vdf) +
guides(size = guide_legend(title='vdf color'))
目前沒有 vanilla ggplot2 選項可以為相同的美學設置兩個比例。
截至今天(2022 年 7 月),“僅”三個軟件包可用於為相同的美學創建多個比例。 這些是
ggnewscale 包帶有三個函數, new_scale_color
、 new_scale_fill
和new_scale
用於除顏色或填充之外的其他美學。
library(ggplot2)
library(ggnewscale)
vdf <- iris[which(iris$Species == "virginica"), ]
ggplot(iris) +
geom_line(aes(x = Sepal.Width, y = Sepal.Length, colour = Species)) +
## the guide orders are not a necessary part of the code
## this is added for demonstrating purpose and because
## the OP wanted a grey line below the Species
scale_color_discrete(guide = guide_legend(order = 1)) +
## add the new scale here
new_scale_color() +
## then add a new color aesthetic, all else as per usual
geom_line(
data = vdf, aes(x = Sepal.Width, y = Sepal.Length, colour = "vdf"),
size = 2
) +
scale_color_manual(NULL, values = "grey", guide = guide_legend(order = 2))
由reprex 包創建於 2022-07-03 (v2.0.1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.