【问题标题】:making line legends for geom_density in ggplot2 in R在 R 中为 ggplot2 中的 geom_density 制作线条图例
【发布时间】:2013-07-06 18:53:55
【问题描述】:

使用 ggplot2,我制作了以下密度图:

ggplot(iris) + geom_density(aes(x=Sepal.Width, colour=Species))

颜色图例(对于每个物种值)显示为一个带有一条线的框,但绘制的密度是一条线。有没有办法让每个物种条目的图例只显示为一条彩色线,而不是一个有一条线穿过它的框?

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    一种可能性是将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")
    

    【讨论】:

    • 第二个解决方案是我正在寻找的 - 但是这不是将密度线重叠绘制,使它们看起来更粗吗?
    • 是的,这会将它们绘制两次。这只是解决此问题的方法。
    • 有没有办法只更改图例而不绘制两次?
    • @user248237dfsf 至少我没有找到仅通过更改图例的解决方案(尽管我尝试了几种方法)。
    • 我明白了。您能否举一个示例,说明如何手动更改图例来做到这一点?假设你使用 geom_density
    【解决方案2】:

    @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)))
    

    【讨论】:

      【解决方案3】:
      ggplot(iris) + 
        stat_density(aes(x=Sepal.Width, colour=Species),
                        geom="line",position="identity")
      

      会想要你想要的。

      【讨论】:

        【解决方案4】:

        你可以通过两次绘制线条

        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:我意识到这个帖子已经很老了,但它今天帮助了我,所以它可能会在某个时候帮助其他人......

        【讨论】:

          猜你喜欢
          • 2014-10-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-05
          • 2015-06-16
          • 1970-01-01
          相关资源
          最近更新 更多