ggplot2画图入门系列之五:时间序列
ggplot2包也能对时间序列数据画图,但在处理惩罚上需要有些留意的处所。下面我们以上证指数为例举办作图,首先操作quantmod包从yahoo数据源获取从1997年以来的数据,存于变量SSEC中,抽取收盘数字,然后别离提取时间数据和指数数值,画图功效如下图。
library(quantmod)
library(ggplot2)
getSymbols(‘^SSEC’,src=’yahoo’,from = ‘1997-01-01’)
close <- (Cl(SSEC))
time <- index(close)
value <- as.vector(close)
p <- ggplot(data.frame(time,value),aes(time,value))
p + geom_line()
们但愿可以或许在图中插手一些其它的说明元素,以富厚视图中所包括的信息。这些信息包罗用差异的颜色区块来暗示“江焦点”和“胡焦点”的执政时期,以及对中国证券市场的若干大事件举办标注。最后的代码和功效如下。yrng <- range(value)
xrng <- range(time)
data <- data.frame(start=as.Date(c(‘1997-01-01′,’2003-01-01’)),end=as.Date(c(‘2002-12-30′,’2012-01-20’)),core=c(‘jiang’,’hu’))
timepoint <- as.Date(c(‘1999-07-02′,’2001-07-26′,’2005-04-29′,’2008-01-10′,’2010-03-31’))
events <- c(‘证券法实施’,’国有股减持’,’股权分置改良’,’次贷危机发作’,’融资融券试点’)
data2 <- data.frame(timepoint,events,stock=value[time%in% timepoint])p + geom_line()
+ geom_rect(aes(NULL,NULL,xmin = start, xmax = end, fill = core),ymin = yrng[1],ymax=yrng[2],data = data)
+ scale_fill_manual(values = alpha(c(‘blue’,’red’),0.2))
+ geom_text(aes(timepoint, stock, label = events),data = data2,vjust = -2,size = 5)
+ geom_point(aes(timepoint, stock),data = data2,size = 5,colour = alpha(‘red’,0.5))