1

我正在尝试添加标题,geom_hline ()但我不知道该怎么做。

我试过geom_hline (aes (yintercept = 18, 'Historical serie'), size = 1.5, col =" # ffff00 ")但它返回一个错误。我拍了“历史系列”,它起作用了,但标题没有出现。

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

期待

在此处输入图像描述

我希望18显示该值及其 Historical serie对黄线的描述。

4

2 回答 2

2

更新:操作请求:

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

在此处输入图像描述

于 2021-05-17T18:28:24.647 回答
0

我在https://community.rstudio.com/t/how-to-add-legend-in-goem-hline-in-r/105127/2的帮助下仅使用 geom_hline ()

选择

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

在此处输入图像描述

于 2021-05-17T21:47:00.227 回答