将图例添加到包含多个元素的ggplot2图中

时间:2016-12-01 14:38:33

标签: r

这是与here类似的问题,但我无法让他的解决方案为我工作。我想在ggplot2图中添加一个图例,当使用多个独立的数据框来生成图时。

以下是基于R:

中可用数据集的示例
a=longley
b=iris
a$scaled=scale(a$Unemployed,center=TRUE,scale=TRUE)
b$scaled=scale(b$Sepal.Length,center=TRUE,scale=TRUE)
ggplot () + 
    geom_density(data=a,aes(x=scaled),fill="red",alpha=0.25) +
    geom_density(data=b,aes(x=scaled),fill="blue",alpha=0.25) +
    scale_colour_manual("",breaks=c("a","b"),values=c("red","blue"))

制作的情节如下: Plot produced 即。没有传说。

我如何为此添加图例?

1 个答案:

答案 0 :(得分:1)

需要非常轻微的语法更改。将fill=部分移动到每个geom中的aes()语句中。

a=longley
b=iris
a$scaled=scale(a$Unemployed,center=TRUE,scale=TRUE)
b$scaled=scale(b$Sepal.Length,center=TRUE,scale=TRUE)
ggplot () + 
    geom_density(data=a,aes(x=scaled,fill="red"),alpha=0.25) +
    geom_density(data=b,aes(x=scaled,fill="blue"),alpha=0.25)

这应该可以单独使用,并为您提供默认的r颜色方案。或者,如果您确实要更改默认值中的颜色,则可以添加手动缩放。但是,由于您希望将比例应用于fill参数,因此请务必指定scale_fill_manual而不是scale_colour_manual

ggplot () + 
    geom_density(data=a,aes(x=scaled,fill="red"),alpha=0.25) +
    geom_density(data=b,aes(x=scaled,fill="blue"),alpha=0.25) +
    scale_fill_manual("",breaks=c("a","b"),values=c("red","blue"))

如果您想要使用color美学来改变线条的颜色,那么就可以使用scale_color_manualscale_colour_manual(相同的东西)选项。

ggplot() + 
    geom_density(data=a, aes(x=scaled, fill="red", color="yellow"), alpha=0.25) +
    geom_density(data=b, aes(x=scaled, fill="blue", color="green"), alpha=0.25) +
    scale_fill_manual(values=c("red","blue")) +
    scale_color_manual(values=c("yellow", "green"))