25

I'd like to add a legend to hline plot.

The head of my subset looks like this

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 the six sites with a line through them. I would ideally like a legend with title = limit and Label 1 (10) = NRW limit and label 2 (75.5)= Geochemical atlas limit.

rawr
  • 20,481
  • 4
  • 44
  • 78
LucySHE
  • 387
  • 1
  • 3
  • 9
  • 1
    Please read [how to provide minimal reproducible examples in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610). Then edit & improve it accordingly. A good post usually provides minimal input data, the desired output data & code tries - all copy-paste-run'able in a new/clean R session. E.g. your example cannot be run as no one except you has got the CSV file, `library(ggplot2)` is missing etc.. – lukeA Aug 24 '16 at 10:54
  • Did you try `show_guide` instead of `show.legend` ? http://stackoverflow.com/questions/17092894/how-to-added-a-custom-legend-for-geom-hline & http://stackoverflow.com/questions/17092894/how-to-added-a-custom-legend-for-geom-hline – bVa Aug 24 '16 at 12:09
  • I have just tried it and I get the error message "`show_guide` has been deprecated. Please use `show.legend` instead" – LucySHE Aug 24 '16 at 14:26

1 Answers1

55

You can use the linetype aesthetic to make a separate legend for the horizontal lines rather than adding them to the existing legend.

To do this we can move linetype inside aes while still mapping to a constant. I used your desired labels as the constant. The legend name and the line type used can be set in scale_linetype_manual. I remove show.legend = TRUE to keep the lines out of the other legend. The legend colors 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

aosmith
  • 34,856
  • 9
  • 84
  • 118
  • Thank you thats amazing!! What an R whizzkid :-) – LucySHE Aug 30 '16 at 08:29
  • Very nice but is there a way to make the dashed line in the legend longer? – Herman Toothrot Apr 12 '18 at 18:25
  • 1
    @HermanToothrot If you want the boxes wider so you can see more of the line you can change the width of the "key" (the legend box). This can be done via the "legend.key.width" argument in `theme`. – aosmith Apr 13 '18 at 14:49
  • @aosmith, i don't quite understand what the values = c(2,2) is doing. What if i wanted to add a third line? – Puddlebunk Jun 11 '18 at 20:47
  • 1
    @Puddlebunk The `values` is where I picked how the lines looked (the "linetype"). You need to gives as many values as you have lines. I chose two of the same type in my example so all the lines look the same; if you had three lines you'd need three linetypes in `values`. See [here](http://sape.inf.usi.ch/quick-reference/ggplot2/linetype) for info on the types of lines you can choose. – aosmith Jun 11 '18 at 20:50
  • @aosmith, Thanks so much! – Puddlebunk Jun 11 '18 at 20:57
  • So, what do you do if you want to specify an actual linetype? – abalter Jul 11 '19 at 04:03
  • @abalter Do you mean you want to map `linetype` to a variable? You should be able to do that and control the line types and legends, although it may take some more work in `override.aes` to keep the two legends separate. Maybe ask a new question that outlines the situation you are in? :) – aosmith Jul 11 '19 at 16:06
  • anyway to switch the relative position of line and point legends? Like if I wanted the "limit" legend on top in this scenario? – user2017023 May 11 '21 at 02:52
  • 1
    @user2017023 See the `order` argument in `guide_legend()` for setting the order of multiple legends. – aosmith May 11 '21 at 16:56
  • It's importance to emphasize that the `colour` argument needs to be outside `aes()`. This was tripping me up until I realized my error. – ahj May 01 '23 at 20:05