Add an entry to the legend for a manually added li

2019-07-07 03:33发布

问题:

I have a histogram created with ggplot (ggplot + geom_bar) and I added a line to it like so:

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

I would like to add an entry to the legend which will indicate that the dashed line is the expected value.

Although there are similar questions on Stack Overflow, I couldn't find the answer to what I need...

Any idea how to do it?

回答1:

It is quite convenient to make reproducible examples in case of ggplot questions, you should do that next time. Here is the answer:

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



标签: r ggplot2