0

我正在使用 ggplot2 制作一些带有图例的密度图,但我无法在最终结果中添加图例。

m <- ggplot(chickwts, aes(x = weight))
m + geom_density(kernel = "gaussian", adjust = .3, colour="green", size=1)+
  geom_density(kernel = "gaussian", adjust = 1, colour="red", size=1)+
  geom_density(kernel = "gaussian",adjust = 5, colour="blue", size=1)+
  geom_density(kernel = "gaussian",adjust = 10, colour="yellow", size=1)+
  geom_density(kernel = "gaussian",adjust = 20, colour="orange", size=1)

我使用了几种在这里找到的语法,但没有一个不起作用。谢谢你。

4

1 回答 1

2

ggplot2它的传说基于美学或传递给aes()函数的参数。通常,您会指定一个因素作为颜色美学,这将自动创建颜色图例。但是,数据集中没有内置的密度分组因子chickwts,因此您必须自己制作比例和标签。

geom_density()您可以定义与您在 中创建的自定义色阶相对应的命名颜色美学,而不是直接在 中定义颜色scale_colour_manual(),如下所示:

m <- ggplot(chickwts, aes(x = weight))
m + geom_density(kernel = "gaussian", adjust = .3, aes(colour=".3"), size=1)+
  geom_density(kernel = "gaussian", adjust = 1, aes(colour="1"), size=1)+
  geom_density(kernel = "gaussian",adjust = 5, aes(colour="5"), size=1)+
  geom_density(kernel = "gaussian",adjust = 10, aes(colour="10"), size=1)+
  geom_density(kernel = "gaussian",adjust = 20, aes(colour="20"), size=1) + 
  scale_colour_manual(values=c(".3"="green", "1"="red", "5"="blue", "10"="yellow", "20"="orange"), name="Densities")

密度图示例

于 2013-10-03T16:32:54.160 回答