caio.valente14
caio.valente14

Reputation: 87

How can I add legend to multiple hlines in ggplot2?


Can anyone help me out with some task?
I have to add 3 geom_hline() to a plot.
One of them is a line that shows the recommended spacing for threes in a forest, and the others are the acceptable upper and lower limits of variation in spacing.
To do so, I'm using geom_hline(), but I'm having a hard time to show the legends in a right way.
Also, the two limits have the same linetype (dashed), being red, and the other one is a solid line in blue color.
Therefore, how can I add legends to these three hlines?
Remembering that I need to have two elements in the legend: brief description of the red dashed line as limit and brief description of the blue solid lines as recommended spacing.
Thanks a lot, guys!

Upvotes: 1

Views: 695

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173813

To show a legend in a ggplot, you should create an aesthetic mapping. The simplest way to do that is to have a seperate little data frame that contains the information you want to show on your hlines.

You haven't provided any sample data, so I've made some up here so that this is a fully reproducible example:

library(ggplot2)

set.seed(69)
main_data <- data.frame(x = rnorm(200, 10), y = rnorm(200, 10))
hline_data <- data.frame(y = c(8, 10, 12), type = factor(c(2, 1, 2)), 
                         stringsAsFactors = FALSE)

ggplot(main_data, aes(x,y)) + 
  geom_point() + 
  geom_hline(data = hline_data, 
             aes(yintercept = y, linetype = type, colour = type)) +
  scale_colour_manual(values = c("blue", "red"), 
                      labels = c("Recommended Spacing", "Limits of spacing"),
                      name = "Key") +
  scale_linetype_manual(values = 1:2, 
                        labels = c("Recommended Spacing", "Limits of spacing"),
                        name = "Key")

Created on 2020-05-19 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions