如何在ggplot2中绘制xts? [英] How to plot xts in ggplot2?

查看:65
本文介绍了如何在ggplot2中绘制xts?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个情节

使用此代码

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 进行绘制的建议将不胜感激?

Any suggestion how to plot it using ggplot2 will be appreciated?

推荐答案

感谢

Thanks to @jlhoward's answer, I used fortify() function to create the plot above using 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) 

这篇关于如何在ggplot2中绘制xts?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆