2014-09-22 98 views
0

我希望通过独特的颜色或形状突出显示时间序列中高于或低于特定值的分段。在示例数据中,我将死亡时间序列分解为其组成部分。我的目标是突出显示当趋势组分的死亡率低于35(1997年至2000年之间的深度)以及剩余组分高于100(高峰)时的细分市场。我试图使用注释,但是这并没有产生我想要的。如何在ggplot2图中突出显示时间序列项目

#Load library and obtain data 

library(gamair) 
library(tsModel) 
library(ggplot2) 
library(reshape2) 
data<-data(chicago) 

## create variables, decompose TS 
chicago$date<-seq(from=as.Date("1987-01-01"), to=as.Date("2000-12-31"),length=5114) 
data<- chicago[,c("date","death")] 
mort <- tsdecomp(data$death, c(1, 2, 15, 5114)) 

## Convert matrix to df, rename, melt 
df<-as.data.frame(mort) 
names(df)[1] <- "Trend" 
names(df)[2] <- "Seasonal" 
names(df)[3] <- "Residual" 
df$date<-seq(as.Date("1987-01-01"), as.Date("2000-12-31"), "day") 
meltdf <- melt(df,id="date") 

## Plot 

ggplot(meltdf,aes(x=date,y=value,colour=variable,group=variable)) + geom_line() + 
theme_bw() + 
ylab("") + xlab("") + 
facet_grid(variable ~ . , scales = "free") + 
theme(legend.position = "none") 
annotate("rect", xmin=1995-01-01,xmax=1996-01-01,ymin= 10, ymax=300, alpha = .2,fill="blue") 

enter image description here

+0

你说:“我试图使用注释,但是这并没有产生我想要的。”结果如何与你想要的不同。你说你想突出独特的颜色或形状的部分,但你有这里的线条,他们已经是不同的颜色。你想在中线改变颜色吗?这里的期望输出到底是什么? – MrFlick 2014-09-22 16:32:00

+0

@MrFlick我的愿望是突出第一个情节中的深度和第三个中的秒杀。注释给出了错误信息。 – Meso 2014-09-22 16:40:20

回答

3

好了,这工作,但我必须承认这是我所希望的更多的工作。

get.box <- function(data) { 
    rng <- range(data$date) + c(-50,50) 
    z <- meltdf[meltdf$date>=rng[1] & meltdf$date <=rng[2] & meltdf$variable==unique(data$variable),] 
    data.frame(variable=unique(z$variable), 
      xmin=min(z$date),xmax=max(z$date),ymin=min(z$value),ymax=max(z$value)) 
} 
hilight.trend <- get.box(with(meltdf,meltdf[variable=="Trend" & value<35,])) 
hilight.resid <- get.box(with(meltdf,meltdf[variable=="Residual" & value>100,])) 
ggplot(meltdf,aes(colour=variable,group=variable)) + 
    geom_line(aes(x=date,y=value)) + 
    theme_bw() + 
    ylab("") + xlab("") + 
    facet_grid(variable ~ . , scales = "free") + 
    theme(legend.position = "none") + 
    geom_rect(data=hilight.trend, alpha=0.2, fill="red", 
      aes(xmax=xmax,xmin=xmin,ymax=ymax,ymin=ymin)) + 
    geom_rect(data=hilight.resid, alpha=0.2, fill="blue", 
      aes(xmax=xmax,xmin=xmin,ymax=ymax,ymin=ymin)) 

你真的不能使用annotate(...)与面,因为你会得到所有方面的相同注释。所以你剩下的东西就像geom_rect(...)。这里的问题是geom_rect(...)为数据中的每一行绘制了一个矩形。因此,您需要为每个variable创建一个只包含一行的辅助数据集,其中包含x和y分钟和最大值。

+0

@jihoward,感谢您的优雅解决方案。我认为这可能会为每个方面做。 – Meso 2014-09-23 07:27:40

相关问题