rggplot2geom-hline

how to add and edit a legend in goem_hline() in R


I'm trying to add a caption to geom_hline () but I don't know how I can do it.

I tried geom_hline (aes (yintercept = 18, 'Historical serie'), size = 1.5, col =" # ffff00 ") but it returns an error. I took 'Historical serie' it worked, but the caption does not appear.

library(tidyr)
library(dplyr)
library(lubridate)
library(ggplot2)

date2<-c('01/01/2000','08/08/2000','16/03/2001','06/09/2001')
name<-c('A','B','A','B')
total<-c(23,25,36,41)
esp<-c(0.363,0.4123,0.09,0.65)

df<-data.frame(date2,name, total, name, esp)%>%
  mutate(date3=as.Date(date2, "%d/%m/%Y"))%>%
  mutate(year_date=as.Date(trunc(as.POSIXlt(date3), "years")))

ggplot(data=df, aes(x=year_date, y=total, fill=name))+ 
  geom_col(position = "dodge")+
  scale_fill_manual(values=c("#08088A","#9F81F7"))+
  theme_light()+labs(fill="rain", title ="rain anual", x="Estation", y="total mm")+
  theme(axis.text.x = element_text(angle = 90))+
  geom_hline(aes(yintercept = 18, 'Historiacal serie'), size=1.5, col="#ffff00")

Expectative

enter image description here

I would like the value 18 to appear as well as its description Historical serie for the yellow line.


Solution

  • Update: OP request:

    p <- ggplot(data=df, aes(x=year_date, y=total, fill=name))+ 
      geom_col(position = "dodge")+
      scale_fill_manual(values=c("#08088A","#9F81F7"))+
      theme_light()+labs(fill="rain", title ="rain anual", x="Estation", y="total mm")+
      theme(axis.text.x = element_text(angle = 90)) 
    
    data_line <- data.frame(yintercept=18, data_line=factor(18))
    
    p + 
      geom_hline(data=data_line, aes(yintercept=yintercept, linetype="18"), size=1.5, col="#ffff00") +
      scale_linetype_manual(name = "Historiacal serie",values = c(1,1)) 
    

    enter image description here