简体   繁体   中英

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!

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 hline s.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM