R根据日期设置绘图背景

时间:2012-02-07 02:57:11

标签: r date plot

我有一张财务活动图表和一些正在运行的金额。enter image description here事情变得有点忙,我在区分财政(6月30日结束)和日历年时遇到了困难。有没有办法根据日期将背景设置为不同的颜色?

换句话说,我可以将背景设置为浅绿色,其中2009-06-30<日期< 2010-07-01

3 个答案:

答案 0 :(得分:5)

查看zoo包中的xblocks.zoo。例如,example(xblocks.zoo)

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

在绘制曲线之前,您可以使用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)