代码之家  ›  专栏  ›  技术社区  ›  shiny

如何在ggplot2中绘制xts?

  •  2
  • shiny  · 技术社区  · 9 年前

    我有这个情节

    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 回复  |  直到 7 年前
        1
  •  3
  •   Community CDub    8 年前

    幸亏 @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)