R根据学期更改ggplot背景的颜色

我有一个股市数据框,我想创建一个彩色背景的地块。但是颜色应该根据学期(一年的上半年或下半年)而定。

在这里您可以获得数据:

library(tidyverse)
library(tidyquant)
library(lubridate)

GDAXI<-tq_get("^GDAXI",get = "stock.prices")

GDAXI%>%
  ggplot(aes(x=date,y=close))+geom_line()

这是我的情节:

R根据学期更改ggplot背景的颜色

现在我想有彩色背景。前半年(jan-june)应该是蓝色,下半年(july-dec)应该是红色。

使用

GDAXI<-GDAXI%>%mutate(semester=lubridate::semester(date))

您可以添加这些学期。 (jan-june == 1和july-dec == 2)

现在我想用geom_rect()

添加彩色背景
GDAXI%>%
  ggplot(aes(x=date,y=close))+geom_line()+ 
  geom_rect(aes(xmin = date,xmax = date,ymin = -Inf,ymax = Inf,fill = semesters)

但这不起作用。有人可以帮我解决这个问题吗?

wzq12 回答:R根据学期更改ggplot背景的颜色

您以前的尝试

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

I am not very good with colours :(

如果您的日期值没有间隔,这应该可以工作。如果您正在处理其他一些有间隔的数据,则可以对其进行一些调整。

我想您需要在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

大家都在问