N.M
N.M

Reputation: 685

Add legend entry for a geom_hline

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?

Upvotes: 3

Views: 592

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48211

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

enter image description here

Upvotes: 5

Related Questions