How to plot xts in ggplot2?

試著忘記壹切 提交于 2019-12-11 01:45:50

问题


I got this plot

using this code

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)

DATA

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]) 

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


回答1:


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) 


来源:https://stackoverflow.com/questions/35215579/how-to-plot-xts-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!