一个时间序列中的多个 geom_rect

Multiple geom_rect over a time series

我试图使用 ggplot2 包多次突出显示时间序列,我创建了一个 data.frame,其中包含所有突出显示的开始日期 (xmin) 和结束日期 (xmax),但是我'我得到:错误: 美学必须是长度一,或与 dataProblems:xmin、xmax、ymin、ymax

相同的长度

密码是:

g.bottom <- ggplot(,aes(x =decimal_date(date), y =C$PE)) +
geom_rect(data=s,aes(xmin=decimal_date(xmin), xmax=decimal_date(xmax),ymin=ymin,ymax=ymax),
alpha=0.1, color="pink", fill="pink")+
geom_line() +
theme_classic() +
theme(plot.margin = unit(c(0,5,10,4),units="points"))+
labs(x="Fecha",y = "PE")

这是数据s:

xmin<-c("2011/07/28","2012/04/09","2012/04/16","2013/04/22","2014/12/08","2014/12/15","2014/12/18")
xmax<-c("2011/08/08","2012/04/12","2012/06/12","2013/04/26","2014/12/11","2014/12/16","2015/04/09")
ymin<- c(-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf)
ymax<-c(Inf,Inf,Inf,Inf,Inf,Inf,Inf)
s<- data.frame(xmin,xmax,ymin,ymax)
transform(s, xmin=as.Date(xmin,format="%Y/%m/%d"))%>%
transform(xmax=as.Date(xmax,format="%Y/%m/%d"))->s
s
        xmin       xmax     ymin ymax
    1 2011-07-28 2011-08-08 -Inf  Inf
    2 2012-04-09 2012-04-12 -Inf  Inf
    3 2012-04-16 2012-06-12 -Inf  Inf
    4 2013-04-22 2013-04-26 -Inf  Inf
    5 2014-12-08 2014-12-11 -Inf  Inf
    6 2014-12-15 2014-12-16 -Inf  Inf
    7 2014-12-18 2015-04-09 -Inf  Inf

这是C

      Date     GSADF    PE
1 26/01/2011 0.7990547 29.07
2 27/01/2011 0.7970526 29.20
3 28/01/2011 0.7947446 28.66
4 31/01/2011 0.7950117 29.05
5 01/02/2011 0.7931063 29.72
6 02/02/2011 0.7900929 29.92

这是适合您的一种方法。我认为关键是使用decimal_date()。您可以在编写 ggplot 代码之前使用该函数并安排数据框。在这里,我在 ggplot 的其中一行中使用了该函数。希望对您有所帮助。

library(lubridate)
library(magrittr)
library(ggplot2)

mydf <- read.table(text = "      Date     GSADF    PE
1 26/01/2011 0.7990547 29.07
2 27/01/2011 0.7970526 29.20
3 28/01/2011 0.7947446 28.66
4 31/01/2011 0.7950117 29.05
5 01/02/2011 0.7931063 29.72
6 02/02/2011 0.7900929 29.92", header = T)

### Convert factor to date
transform(mydf, Date = as.Date(Date, format = "%d/%m/%Y")) -> mydf

mydf2 <- read.table(text = "     xmin       xmax     ymin ymax
1 2011-07-28 2011-08-08 -Inf  Inf
2 2012-04-09 2012-04-12 -Inf  Inf
3 2012-04-16 2012-06-12 -Inf  Inf
4 2013-04-22 2013-04-26 -Inf  Inf
5 2014-12-08 2014-12-11 -Inf  Inf
6 2014-12-15 2014-12-16 -Inf  Inf
7 2014-12-18 2015-04-09 -Inf  Inf", header = T)

### Convert factor to date
transform(mydf2, xmin = as.Date(xmin, format = "%Y-%m-%d")) %>%
transform(xmax = as.Date(xmax, format = "%Y-%m-%d")) -> mydf2


### Decial dates are necessary. Use decimal_date() in the lubridate package.

ggplot() + 
geom_rect(data = mydf2, aes(xmin = decimal_date(xmin), xmax = decimal_date(xmax), ymin = ymin, ymax = ymax),
      alpha = 0.1, color = "pink", fill = "pink") +
geom_line(data = mydf, aes(x = decimal_date(Date), y = PE))