How to add a legend to hline?

I would like to add a legend to the hline plot.

The head of my subset is as follows

Site Date Al 1 Bo6 2014-10-07 152.1 2 Bo1 2014-10-07 157.3 3 Bo3 2014-10-07 207.1 4 Bo4 2014-10-07 184.3 5 Bo5 2014-10-07 23.2 13 Bo6 2014-10-14 96.8 

My code is as follows:

 require(ggplot2) require(reshape2) require(magrittr) require(dplyr) require(tidyr) setwd("~/Documents/Results") mydata <- read.csv("Metals sheet Rwosnb5.csv") mydata <- read.csv("Metals sheet Rwosnb5.csv") L <- subset(mydata, Site =="Bo1"| Site == "Bo2"| Site == "Bo3"| Site == "Bo4"| Site == "Bo5" | Site == "Bo6", select = c(Site,Date,Al)) L$Date <- as.Date(L$Date, "%d/%m/%Y") I <- ggplot(data=L, aes(x=Date, y=Al, colour=Site)) + geom_point() + labs(title = "Total Al in the Barlwyd and Bowydd in Pant-yr-afon sites B4-B9 2014-2015.", x = "Month 2014/2015", y = "Total concentration (mg/L)") + scale_y_continuous(limits = c(0, 500)) + scale_x_date(date_breaks = "1 month", date_labels = "%m") I + geom_hline(aes(yintercept= 10), linetype = 2, colour= 'red', show.legend =TRUE) + geom_hline(aes(yintercept= 75.5), linetype = 2, colour= 'blue', show.legend = TRUE) 

For some reason, the legend does not work - the legend has six sites with a direct line through them. I would ideally like the legend with the title = limit and label 1 (10) = NRW limit and label 2 (75.5) = geochemical atlas limit.

+5
source share
1 answer

You can use linetype aesthetics to create a separate legend for horizontal lines rather than adding them to an existing legend.

To do this, we can move linetype inside aes , while maintaining the mapping to a constant. I used your needed shortcuts as a constant. The name of the legend and the type of line used can be set to scale_linetype_manual . I delete show.legend = TRUE so that the lines do not coincide with other legends. The colors of the legend are fixed in override.aes .

 I + geom_hline(aes(yintercept= 10, linetype = "NRW limit"), colour= 'red') + geom_hline(aes(yintercept= 75.5, linetype = "Geochemical atlas limit"), colour= 'blue') + scale_linetype_manual(name = "limit", values = c(2, 2), guide = guide_legend(override.aes = list(color = c("blue", "red")))) 

enter image description here

+12
source

All Articles