您以前的尝试
geom_rect(aes(xmin = date,xmax = date,ymin = -Inf,ymax = Inf,fill = semesters)
沿着正确的轨道。这是行不通的,因为xmin与xmax相同,所以没有矩形吗?另外,我认为geom_rect与-Inf和+ Inf不兼容,与geom_text等不同。
library(lubridate)
GDAXI<-GDAXI%>%mutate(semester=semester(date))
# define y limits
LIMS = range(GDAXI$close,na.rm=T)
# we need to define the semesters and year,i.e the boxes we want to plot
GDAXI$semester_grp = semester(GDAXI$date,with_year = TRUE)
# here we create the coordinates of the rectangle
# basically x1 is start of semester
# x2 is end of semester
rectData = GDAXI %>% group_by(semester_grp) %>%
summarize(x1=min(date),x2=max(date),y1=LIMS[1],y2=LIMS[2],semester=unique(semester))
# we call ggplot on the two separate data frames
ggplot()+
geom_rect(data=data.frame(rectData),mapping=aes(xmin=x1,xmax=x2,ymin=y1,ymax=y2,fill=factor(semester)),alpha=0.3) +
geom_line(data=GDAXI,aes(x=date,y=close))+
scale_fill_manual(values=c("blue","red"),name="Semester")+
theme_bw()
如果您的日期值没有间隔,这应该可以工作。如果您正在处理其他一些有间隔的数据,则可以对其进行一些调整。
我想您需要在geom_rect中使用scale_fill_manual和alpha才能正确显示颜色:)
,
此外,我找到了另一种解决方案:
GDAXI<-GDAXI%>%mutate(semester=lubridate::semester(date),year=lubridate::year(date))
GDAXI<-GDAXI%>%group_by(year,semester)
table<-GDAXI%>%summarise(x1=head(date,1),x2=tail(date,y1=-Inf,y2=Inf,color=head(semester,1))%>%
mutate(color=ifelse(color==1,"red","blue"))
GDAXI%>%
ggplot()+
geom_line(aes(x=date,y=close))+
geom_rect(data=table,aes(xmin=x1,ymax=y2),fill=table$color,alpha=0.3)+
theme_bw()
本文链接:https://www.f2er.com/3165995.html