how to add 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 would like the name "historical serie" and the value "'18" to appear in front of the line, as in the example in the image.

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.

my code

> 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))

Hi,

I can't reproduce your code, but you can use geom_hline(aes(.., linetype =... ) ) with scale_linetype_manual() . Try to add

geom_hline(aes(yintercept = 18, linetype = "historical average"), colour = "blue") +
scale_linetype_manual(name ="", values = c('dotted')) #for e. g. dotted hline

to your code and see if it gives you what you're looking for.

JW

1 Like

Amazing, I achieved.

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 = "51"), colour = "green", size=1.5) +
scale_linetype_manual(name ="IQA BOM", values = c('solid'))

thanks vrey much JW

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.