【问题标题】:ggplot2 create a geom_hline legend without wasting the barplot oneggplot2 创建一个 geom_hline 图例而不浪费 barplot 一个
【发布时间】:2016-10-23 01:57:40
【问题描述】:

我正在尝试为使用 ggplot2 制作的复合图表生成一个好的图例,其中有一个闪避的条形图和一条用于显示土壤中钡的参考值的水平线。问题是线图图例的特征也是“污染”的条形图之一。我已经看到类似的主题试图调整提出的其他解决方案,但没有任何显着结果。

这是我的例子:

数据框:

       Position   Year   Value
       Position 1 1999    12
       Position 2 1999    14
       Position 3 1999    15
       Position 1 2000    13
       Position 2 2000    11
       Position 3 2000    21
       Position 1 2001    12
       Position 2 2001    13
       Position 3 2001    16

代码:

    ggplot(input, aes(fill=Year , x=Position, y=Value)) +

    geom_bar(stat="identity",
    position="dodge",  size=0.1, width=0.5, show.legend=TRUE) +
    labs(title="Barium concentration in the soil") +
    xlab("Samples") +
    ylab("Concentration in ng/kg") +
    scale_y_continuous(limits = c(0, 30)) +
    #color of barplot
    scale_fill_manual(values=c("grey40", "grey70", "grey80")) +

    #limit value
    geom_hline(aes(yintercept=40, colour = "red"), size=0.9, alpha=0.8, show.legend=TRUE )

这是图表

如您所见,hline 图例的功能正在浪费条形图。

【问题讨论】:

  • 您需要将colour="red' 从您的geom_hline 移出aes。
  • 通过将 'colour="red'" ' 命令移到 'aes' 之外,您只需从图表中删除线图例。相反,我想保留它:“geom_hline”图例是可以的。问题是barplot图例被bar simbols内的黑线污染了,这个问题与'geom_hline'图例的创建有关。
  • 数据的表示方式不能与代码一起使用。例如,年份变量必须格式化为字符,否则将不起作用。我建议使用 dput(your_data.frame) 并将其添加到您的问题中。

标签: r ggplot2 legend


【解决方案1】:

你可以这样做:

ggplot(input, aes(fill=Year , x=Position, y=Value)) +
  geom_bar(stat="identity", position="dodge",  size=0.1, width=0.5) +
  labs(title="Barium concentration in the soil") + xlab("Samples") +
  ylab("Concentration in ng/kg") +
  scale_y_continuous(limits = c(0, 30))+
  geom_hline(aes(yintercept=20, colour="limit"), size=0.9, alpha=0.8) +
  scale_fill_manual(values=c("grey40", "grey70", "grey80")) +
  scale_color_manual(name="Foo", values=c(limit="red")) +
  theme(legend.key = element_rect(fill = "white", colour = "white"))

情节如下所示:

【讨论】:

  • 谢谢!!!完美而清晰的解决方案!有没有可能改变图例中红线后面的灰色背景?
  • 不客气。我编辑了我的遮阳篷。代码现在更惯用了,图例最后一个条目中的矩形背景现在是白色的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多