我有一个用ggplot(ggplot + geom_bar)创建的直方图,并且像这样添加了一条线:

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


我想在图例中添加一个条目,该条目将指示虚线是期望值。

尽管Stack Overflow也有类似的问题,但我找不到所需的答案...

知道怎么做吗?

最佳答案

在发生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)))

07-26 09:36