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

144 views Asked by At

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.

2

There are 2 answers

4
TarJae On BEST ANSWER

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

0
wesleysc352 On

I got it with help from https://community.rstudio.com/t/how-to-add-legend-in-goem-hline-in-r/105127/2 using only geom_hline ()

alternative

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)

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, linetype = "18"), colour = "green", size=1.5) +
scale_linetype_manual(name ="Historical serie", values = c('solid'))

enter image description here