开发者

Plotting a moving time series curve

For a time series curve:

  1. I want to fix the dimensions and labels of the graph.
  2. Then plot a moving curve on the graph for some time series analysis. For example, a convolution.

How would I ach开发者_开发技巧ieve this with R?


Two quick points:

  • the old school trick is to write a sequence of gif files individually in a loop, and to then use a tool like imagemagick to 'glue' them together into an animated gif

  • there are also higher-level packages such as the award-winning animation that help with this; some features may be platform-dependent


Here is some basic code to get you started (you can add the grid lines, legend, etc. if they are important to you):

plotfun <- function(x) {
    plot( c(-0.5,-0.5,0.5,0.5), c(0,1,1,0), col='blue', xlim=c(-2,2),
         type='l', xlab='', ylab='' )
    if( x > -1 && x < 0 ) {
        polygon( c(-0.5, -0.5, x+0.5, x+0.5), c(0,1,1,0), col='yellow', border=NA )
        lines( c(-0.5, -0.5, 0.5, 0.5), c(0,1,1,0), col='blue' )
        lines( c(-1,x), c(0,x+1) )
    } else if( x >= 0 && x < 1 ) {
        polygon( c(x-0.5, x-0.5, 0.5, 0.5), c(0,1,1,0), col='yellow', border=NA )
        lines( c(-0.5, -0.5, 0.5, 0.5), c(0,1,1,0), col='blue' )
        lines( c(-1,0,x), c(0,1,1-x) )
    } else if (x >= 1) {
        lines( c(-1,0,1), c(0,1,0) )
    }
    abline(v=x, lty=3)
    lines( c(x-0.5,x-0.5,x+0.5,x+0.5), c(0,1,1,0), col='red' )
}

dev.new(height=3, width=6)

for(i in seq(-2.5, 2.5, 0.05) ) {
    plotfun(i)
    Sys.sleep(0.1)
}

you could replace the for loop with a repeate or while loop and control the increment and reset automatically to do multiple cycles.

You could also remove the Sys.sleep and put that inside a call to saveMovie, saveHTML, or other function from the animation package to create a file with the animation.

Another approach that lets you control the animation by moving a slider back and forth is:

library(TeachingDemos)

tkexamp( plotfun, list(x=list('slider', from=-2.5, to=2.5, resolution=0.01)),
    vscale=1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜