【问题标题】:Add legend entry for a geom_hline为 geom_hline 添加图例条目
【发布时间】:2014-01-21 17:49:38
【问题描述】:

我有一个使用 ggplot (ggplot + geom_bar) 创建的直方图,我在其中添加了一行,如下所示:

+ geom_hline(aes(yintercept = 0.05), linetype = 'dashed')

我想在图例中添加一个条目,表明虚线是预期值。

虽然Stack Overflow上有类似的问题,但我找不到我需要的答案...

知道怎么做吗?

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    在 ggplot 问题的情况下制作可重现的示例非常方便,下次你应该这样做。答案如下:

    ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar(position = "dodge") + 
    # linetype has to be aes; show_guide = TRUE is important
      geom_hline(aes(yintercept = 1500, linetype = "Expected value"), 
                 show_guide = TRUE) + 
    # 2 means dashed
      scale_linetype_manual("Title", values = 2) +
    # This fixes some problems, try linetype = 1 and another legend will be ruined
      guides(fill = guide_legend(override.aes = list(linetype = 0)))
    

    【讨论】:

      猜你喜欢
      • 2019-08-21
      • 1970-01-01
      • 2013-06-10
      • 2021-09-12
      • 2017-12-04
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多