2014-09-22 59 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

相關問題