簡體   English   中英

如何在ggplot2中為相同的美學設置多個圖例/比例?

[英]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 月),“僅”三個軟件包可用於為相同的美學創建多個比例。 這些是

  • 中繼器包(維護者克勞斯威爾克)-不在 CRAN 上
  • ggh4x 包(在 CRAN 上,維護者 Teun van den Brand)
  • ggnewscale 包(在 CRAN 上,維護者 Elio Campitelli)

ggnewscale 包帶有三個函數, new_scale_colornew_scale_fillnew_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM