如何在ggplot2中绘制xts?

时间:2016-02-05 03:00:01

标签: r ggplot2 xts zoo

我得到了这个情节

enter image description here

使用此代码

library(xts) 
library(zoo)
plot.new()
par(mai=c(2, 2, 1, 1)) 
plot(nats[,2], ylim=c(0, 2.5), 
     xlab = "", ylab="", main="",  major.ticks="months", 
     major.format="%d-%b-%Y", minor.ticks=FALSE, las=1, cex.axis=0.8) 
points(nats[rans,2], col="darkgrey", pch=16, cex=0.5) 
points(M1[rans], col="red", pch=16, cex=0.5) 
points(M2[rans], col="blue", pch=16, cex=0.5) 
points(M3[rans], col="green", pch=16, cex=0.5) 
legend(x="topright", 
       legend=c("a", "Actual value", "M1","M2","M3"), 
       col=c("Black", "Grey", "Red","Blue","Green"), 
       lwd=1, lty=c(1,NA,NA,NA, NA), 
       pch=c(NA,16,16,16,16), merge=FALSE, cex=0.6)

数据

set.seed(123) 
date <- as.Date(seq(as.Date("2003-01-01"), 
                    as.Date("2003-05-31"), by = 1), format="%Y-%m-%d")
a <- runif(151, 0.005, 2.3) 
df <- data.frame(date, a)

#select 30 random samples 
rans<-sample(length(df$a), 30) 
df$a.rm <- df$a

#set the values for the selected rows as NA 
df[rans, 3]<-NA

#reorder columns 
df <- subset(df, select=c(1,3,2))

# test 3 methods for filling NA 
nats<-xts(df[,-1], as.POSIXct(df$date))
M1<-na.locf.default(nats[,1])
M2<-na.approx(nats[,1])
M3<-na.spline(nats[,1]) 

任何有关如何使用ggplot2绘图的建议都将受到赞赏?

1 个答案:

答案 0 :(得分:4)

感谢@jlhoward's answer,我使用fortify()函数使用ggplot2

创建上图
library(ggplot2) 
nats1 <- fortify(nats)
M1.1 <- fortify(M1)
M2.2 <- fortify(M2)
M3.3 <- fortify(M3)
cols <- c("a"="black", "Actual value" = "black","M1"="red","M2"="blue", "M3" = "green") 
ggplot(data=nats1, aes(x=Index, y=a))+
       geom_line(aes())+
       geom_point(data=nats1[rans,], aes(x=Index, y=a,   color="Actual value"),  size=2)+ 
       geom_point(data=M1.1[rans,], aes(x=Index, y=a.rm, color="M1"), size=2)+ 
       geom_point(data=M2.2[rans,], aes(x=Index, y=a.rm, color="M2"), size=2)+ 
       geom_point(data=M3.3[rans,], aes(x=Index, y=a.rm, color="M3"), size=2)+ 
       scale_colour_manual(name=" ", values=cols)