【发布时间】:2013-07-06 18:53:55
【问题描述】:
使用 ggplot2,我制作了以下密度图:
ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species))
颜色图例(对于每个物种值)显示为一个带有一条线的框,但绘制的密度是一条线。有没有办法让每个物种条目的图例只显示为一条彩色线,而不是一个有一条线穿过它的框?
【问题讨论】:
使用 ggplot2,我制作了以下密度图:
ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species))
颜色图例(对于每个物种值)显示为一个带有一条线的框,但绘制的密度是一条线。有没有办法让每个物种条目的图例只显示为一条彩色线,而不是一个有一条线穿过它的框?
【问题讨论】:
一种可能性是将stat_density() 与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:我意识到这个帖子已经很老了,但它今天帮助了我,所以它可能会在某个时候帮助其他人......
【讨论】: