如何在ggplot2中为相同的美学设定多个图例/比例尺?

9
我正在使用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中添加一个图例,在这种情况下将显示一条灰色线条,位于iris的图例下方?谢谢。

1
现在你可以使用 ggnewscale,它可以让你为颜色/填充添加一个新的比例尺槽位。点击此处获取更多信息:https://eliocamp.github.io/ggnewscale/。 - RobertoSupe
2个回答

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)

输入图像描述

编辑:我认为对于相同的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'))

enter image description here


@agstudy:但我希望该线是灰色的,并且图例是分开的。请注意,当您执行上述操作时,它会更改所有其他物种的图例为粗体线条,即使其他物种没有绘制粗体线条,因此看起来很混乱。有没有办法获得两个图例? - user248237
3
@user248237dfsf,agstudy是正确的。ggplot2的设计不允许同一美学属性拥有多个图例(例如两个颜色图例、两个填充图例等)。 - joran

6

目前,vanilla ggplot2没有设置同一美学的两个比例尺的选项。

截至2022年7月,仅有三个软件包可用于创建同一美学的多个比例尺。它们是:

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 package (v2.0.1)于2022-07-03创建


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接