使用 ggplot2,我制作了以下密度图:
ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species))
颜色图例(对于每个 Species 值)显示为一个带有一条线的框,但绘制的密度是一条线。有没有办法让图例显示为每个物种条目的彩色线,而不是一个有一条线的框?
一种可能性是使用stat_density()with geom="line"。只有在这种情况下,才会只有上线。
  ggplot(iris)+
    stat_density(aes(x=Sepal.Width, colour=Species),
                     geom="line",position="identity")
如果您还需要整个区域(所有线条),那么您可以结合geom_density()使用show_guide=FALSE(删除图例),而stat_density()不是仅使用水平线添加图例。
ggplot(iris) + 
  geom_density(aes(x=Sepal.Width, colour=Species),show_guide=FALSE)+
  stat_density(aes(x=Sepal.Width, colour=Species),
                  geom="line",position="identity")

@liesb 在答案中使用的show_guide函数在 ggplot 3.0.0 下已弃用;它已更改为show.legend:
ggplot(iris) + 
geom_density(aes(x=Sepal.Width, colour=Species),show.legend=FALSE) +
stat_density(aes(x=Sepal.Width, colour=Species),
             geom="line",position="identity", size = 0) + 
guides(colour = guide_legend(override.aes=list(size=1)))
ggplot(iris) + 
  stat_density(aes(x=Sepal.Width, colour=Species),
                  geom="line",position="identity")
会想要你想要的。
您可以通过两次绘制线条
ggplot(iris) + 
geom_density(aes(x=Sepal.Width, colour=Species),show_guide=FALSE) +
stat_density(aes(x=Sepal.Width, colour=Species),
             geom="line",position="identity", size = 0) + 
guides(colour = guide_legend(override.aes=list(size=1)))
ps:很抱歉没有评论明显正确的答案——缺乏代表问题:)
pps:我意识到线程已经很老了,但它今天帮助了我,所以它可能会在某个时候帮助别人......