如何在ggplot2中为相同的审美设置多个图例? [英] How to set multiple legends for the same aesthetic in ggplot2?

查看:208
本文介绍了如何在ggplot2中为相同的审美设置多个图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #虹膜数据的子集
vdf = iris [其中(iris $ Species ==virginica),]
#来自虹膜和vdf的绘图
ggplot(虹膜)+
geom_line(aes(x = Sepal.Width,y = Sepal.Length,color = Species))+
geom_line(aes(x = Sepal.Width,y = Sepal.Length),color =gray,size = 2,
data = vdf)

传奇 color iris ,而不是从 vdf 。我怎样才能让ggplot2在 data = vdf 中添加一个图例,在这种情况下,这个图例会在 iris ?谢谢。

解决方案

您应该将颜色设置为 aes 以显示它在图例中。

 #虹膜数据的子集
vdf = iris [which(iris $ Species == virginica),]
#来自虹膜和vdf的绘图
library(ggplot2)
ggplot(虹膜)+ geom_line(aes(x = Sepal.Width,y = Sepal.Length,color =物种))+
geom_line(aes(x = Sepal.Width,y = Sepal.Length,color =gray),
size = 2,data = vdf)



编辑我认为你不可能拥有同一个aes的多个传说。这里有一个解决方法:

pre $ library $ g
ggplot +
geom_line(aes(x = Sepal.Width,y = Sepal.Length,color = Species))+
geom_line(aes(x = Sepal.Width,y = Sepal.Length,size = 2),color =gray,$ b $ (大小= guide_legend(title ='vdf color'))


I am plotting data from multiple dataframes in ggplot2 as follows:

# 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)

the legend for colour includes only entries from iris, and not from vdf. how can I make ggplot2 agg a legend from data=vdf, which in this case would be a gray line below the legend for iris? thanks.

解决方案

You should set the color as an aes to show it in the legend.

# 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)

EDIT I don't think you can't have a multiple legends for the same aes. here aworkaround :

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",
            override.aes=TRUE,  data=vdf) +
   guides(size = guide_legend(title='vdf color'))

这篇关于如何在ggplot2中为相同的审美设置多个图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆