[英]Adding a legend to a ggplot2 plot which contains multiple elements
这是与此处类似的问题,但是我无法获得他们的解决方案来为我工作。 当使用多个独立数据框生成图时,我想在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"))
我该如何添加图例?
需要非常小的语法更改。 将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
,则可以采用color
美观的方式进行操作,然后可以使用scale_color_manual
或scale_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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.