如何在ggplot2中为同一美学设置多个图例?

6 plot r 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)
Run Code Online (Sandbox Code Playgroud)

图例colour仅包含条目iris,而不包括条目vdf.我怎样才能使ggplot2聚合成一个传说data=vdf,在这种情况下,它将是传说下面的灰线iris?谢谢.

Tje*_*ebo 8

目前没有普通的 ggplot2 选项可以为相同的美感设置两个比例。

截至今天(2022 年 7 月),“只有”三个软件包可用于创建多个具有相同美感的比例。这些都是

  • 中继器包(维护者 Claus Wilke) - 不在 CRAN 上
  • ggh4x 包(在 CRAN 上,维护者 Teun van den Brand)
  • ggnewscale 包(在 CRAN 上,维护者 Elio Campitelli)

ggnewscale 包具有三个函数:new_scale_colornew_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))
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2022 年 7 月 3 日创建(v2.0.1)


ags*_*udy 7

您应该将颜色设置为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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑我认为你不能为同一个人提供多个传说.这里的工作方式:

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'))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @ user248237dfsf agstudy是正确的.**ggplot2**按设计不允许同一美学的多个图例(即2色图例,2个填充图例等). (2认同)