绘制R中时间序列数据上任何函数的点

时间:2017-01-15 13:15:40

标签: r plot time-series

我正试图在任何TS数据上绘制点。 我的主要问题是如何将数据传输到此功能。 它应该能够绘制该TS的点数,即每年增加5%

require(datasets)
require(zoo)
## ploting
MyPlot <- function(x=ldeaths,Events, pch = 19, col = 'red', cex = 1)
{ 
 plot(x)
 myData <- as.zoo(x)
 points(myData[Events], pch = pch, col = col, cex = cex)
  }

### My problem
MyPlot(x = anyTimeSeriesdata, Events = anyFunOperatingOnTS)

如何定义anyFunOperatingOnTS

1 个答案:

答案 0 :(得分:1)

检查此功能。您可以根据需要传递percent = 0.05 >5%或其他值。

MyPlot <- function(x = ldeaths, Events = TRUE, pch = 19, col = 'red', 
                        cex = 1, xlab = "Date", ylab = "Deaths", percent = 0.05){     
    #Convert x to data.frame 
    intermediate_data = as.data.frame(t(matrix(x, 12,
                        dimnames = list(month.abb, unique(floor(time(x)))))))

    #Make year (from rownames) a column
    intermediate_data$year = rownames(intermediate_data)

    #Melt data into long form 
    require(reshape2)
    intermediate_data = melt(intermediate_data, id = "year")

    #Convert to POSIXct format (I've added 15 as day for each month)
    intermediate_data$date = as.POSIXct(paste(intermediate_data$year,
           intermediate_data$variable,"15",sep = "/"),format = "%Y/%b/%d")

    #Retain only the relevant columns                       
    intermediate_data = intermediate_data[,c(4,3)]

    #Order by date
    intermediate_data = intermediate_data[with(intermediate_data, order(date)), ]

    #Compute difference
    intermediate_data$diff = c(0,diff(x = intermediate_data$value,
                        lag = 1, differences = 1))

    #Find out the rows for which difference is greater than percent (default is 5%)
    for (i in 2:nrow(intermediate_data)){
        if (intermediate_data$diff[i]/intermediate_data$value[i-1] > percent){
            intermediate_data$Remarks[i] = paste(">",percent,sep="")
        } else {
            intermediate_data$Remarks[i] = paste("!>",percent,sep="")
        }
    }

    #Separate the ones with greater than 5% into another data.frame
    timeseries = subset(intermediate_data, 
             intermediate_data$Remarks == paste(">",percent,sep=""))

    #Plot the lines
    plot(x = intermediate_data$date, y = intermediate_data$value, 
                         type = "l", xlab = xlab, ylab = ylab)

    #Plot the points for greater than percent if EVENTS == TRUE
    if (Events == TRUE){
        points(x = timeseries$date, y = timeseries$value, 
                       pch = pch, col = col, cex = cex)
    }
}