Ken_Rob
Ken_Rob

Reputation: 1

R ggplot legend formatting for geom_hline

Here is the head of the data:

LocationName Section Event_Date           Year Species_Code  Area YOYpop ADTpop TOTpop YOYmnwt ADTmnwt
  <chr>        <chr>   <dttm>              <dbl> <chr>        <dbl>  <dbl>  <dbl>  <dbl>   <dbl>   <dbl>
1 Cosby Creek  2       2013-06-04 00:00:00  2013 BKT           410       9     73     82     2.8    25.3
2 Cosby Creek  2       2014-06-03 00:00:00  2014 BKT           693.     62     34     92     1.7    36.1
3 Cosby Creek  2       2015-06-12 00:00:00  2015 BKT           454.     63     46    109     2.3    28.4
4 Cosby Creek  2       2016-06-13 00:00:00  2016 BKT           506.     20     56     76     3.2    30.2
5 Cosby Creek  2       2017-06-12 00:00:00  2017 BKT           442.     13     19     32     6.2    45.3
6 Cosby Creek  2       2000-06-01 00:00:00  2000 BKT           563.     33     37     72     3      32.5

Here is the code:

library(tidyverse)    
select(Year, YOYBiom, ADTBiom) %>%
  gather(key = Age, value = Biomass, YOYBiom, ADTBiom)
  ggplot(FISH.biom, aes(x = Year, y = Biomass)) +
  geom_point(aes(colour = Age)) +
  scale_colour_manual(values = c("orange", "blue")) +
  geom_hline(aes(yintercept = c(quantile(FISH$YOYBiom, 0.025)), linetype = "YOY Lower CL"), colour = "blue") +
  geom_hline(aes(yintercept = c(quantile(FISH$YOYBiom, 0.975)), linetype = "YOY Upper CL"), colour = "blue") +
  geom_hline(aes(yintercept = c(quantile(FISH$ADTBiom, 0.025)), linetype = "ADT Lower CL"), colour = "orange") +
  geom_hline(aes(yintercept = c(quantile(FISH$ADTBiom, 0.975)), linetype = "ADT Upper CL"), colour = "orange") +
  labs(title = "Annual Biomass", subtitle = "(Cosby Creek)", x = "Year", y = "Biomass (kg/ha)")+ #adds labels
  theme_bw(base_size = 10)

Here is the output plot:

enter image description here

As you can see, there are a couple of issues. I am looking to:

  1. Have the colors in the legend for the geom_hlines match what they are on the graph
  2. replace the title/label of the legend for geom_hline with something more meaningful instead of 'linetype'

I found help here: How to add a legend to hline?

But I've hit a bit of a wall.

Thanks,

Upvotes: 0

Views: 654

Answers (1)

c6user
c6user

Reputation: 55

You need to manually set the legend using scale_linetype_manual()

Upvotes: 0

Related Questions