R根据日期设置绘图背景

问题描述:

我有一张金融活动图表和一对夫妇跑步金额。 enter image description here事情变得有点忙,我在区分财政(截至6月30日)和历年之间出现问题。有没有办法根据日期将背景设置为不同的颜色?R根据日期设置绘图背景

换句话说我可以设置背景为lite绿色哪里2009-06-30 <日期< 2010-07-01?

应用@ G-Grothendieck和@vincent的两条建议 - 在zoo包内使用rectzoo非常适合时间序列的任何可视化。

library(zoo) 
#random data combined with time series that starts in 2009-01 
v <- zooreg(rnorm(37), start = as.yearmon("2009-1"), freq=12) 
plot(v, type = "n",xlab="",xaxt="n") 
#this will catch some min and max values for y-axis points in rect 
u <- par("usr") 
#plot green rect - notice that x-coordinates are defined by date points 
rect(as.yearmon("2009-6-30"), u[3], as.yearmon("2010-7-1"), u[4], 
     border = 0, col = "lightgreen") 
lines(v) 
axis(1, floor(time(v))) 
#customized x-axis labels based on dates values 
axis(1,at=c(2009.4, 2010.5),padj=-2,lty=0,labels=c("start","end"),cex.axis=0.8) 

enter image description here

+0

非常感谢,这是非常有帮助! – screechOwl 2012-02-10 19:24:21

在绘制曲线之前,您可以绘制灰色矩形,并使用rect。 您还需要绘图区域的尺寸:它们在par("usr")中。

library(quantmod) 
getSymbols("A") 
plot(index(A), coredata(Ad(A)), type="n") 
# This example uses calendar years: adapt as needed 
dates <- c( 
    ISOdate(year(min(index(A))),  1, 1), 
    ISOdate(year(max(index(A))) + 1, 1, 1) 
) 
dates <- as.Date(dates) 
dates <- seq.Date(dates[1], dates[2], by="2 year") 
rect( 
    dates, 
    par("usr")[3], 
    as.Date(ISOdate(year(dates) + 1, 1, 1)), 
    par("usr")[4], 
    col="grey", 
    border=NA 
) 
lines(index(A), coredata(Ad(A)), lwd=3) 

在动物园包中检出xblocks.zoo。例如example(xblocks.zoo)