Reputation: 1453
I have a stock-market dataframe and I want to create a plot with a colored background. But the color should be based on the semesters (first or second half of the year).
Here you can get the data:
library(tidyverse)
library(tidyquant)
library(lubridate)
GDAXI<-tq_get("^GDAXI", get = "stock.prices")
GDAXI%>%
ggplot(aes(x=date, y=close))+geom_line()
Now I would like to have a colored background. The first half year(jan-june) should be blue an the second half (july-dec) should be red.
With
GDAXI<-GDAXI%>%mutate(semester=lubridate::semester(date))
you can add these semesters. (jan-june ==1 and july-dec ==2)
And now I want to add a colored background with geom_rect()
GDAXI%>%
ggplot(aes(x=date, y=close))+geom_line()+
geom_rect(aes(xmin = date, xmax = date, ymin = -Inf, ymax = Inf, fill = semesters)
But this is not working. Can someone help me to solve this problem?
Upvotes: 1
Views: 127
Reputation: 1453
Moreover I found another solution:
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,1),
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, xmax=x2, ymin=y1, ymax=y2), fill=table$color, alpha=0.3)+
theme_bw()
Upvotes: 1
Reputation: 46908
your previous try with this
geom_rect(aes(xmin = date, xmax = date, ymin = -Inf, ymax = Inf, fill = semesters)
is along the right track. It doesn't work because xmin will be the same as xmax, so there is no rectangle? Also I think geom_rect doesn't work with -Inf and +Inf, unlike geom_text etc..
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()
This should work if your date values don't have gaps.. You can tweak it a bit if you are working on some other data with gaps.
And I guess you need to play around with scale_fill_manual and alpha in geom_rect to get the colors right :)
Upvotes: 1