Real time, auto updating, incremental plot in R

user1507176 picture user1507176 · Jul 6, 2012 · Viewed 13.9k times · Source

I'm trying to make a dynamic plot, sort of like auto updating, incremental, possibly real time. I want to accomplish something like this http://www.youtube.com/watch?v=s7qMxpDUS3c

This is what I have done so far. Suppose you have a time series in a data.frame called temp. First column is the time and the second column is where the values are.

for(i in 1: length(temp$Time[1:10000]))
{
flush.console()
plot(temp$Time[i:i+100],temp$Open[i:i+100],
xlim=c(as.numeric(temp$Time[i]),as.numeric(temp$Time[i+150])),
ylim=c(min(temp$Open[i:i+100]),max(tmep$Open[i:i+120])))
Sys.sleep(.09)
}

This does plot incrementally but I don't get the 100 units long time series instead i get just one point updating.

Answer

nograpes picture nograpes · Jul 6, 2012

Do you want to do something like this?

n=1000
df=data.frame(time=1:n,y=runif(n))
window=100
for(i in 1:(n-window)) {
    flush.console()
    plot(df$time,df$y,type='l',xlim=c(i,i+window))
    Sys.sleep(.09)
}

Going through your code:

# for(i in 1: length(temp$Time[1:10000])) { 
for (i in 1:10000) # The length of a vector of 10000 is always 10000
    flush.console()
    # plot(temp$Time[i:i+100],temp$Open[i:i+100],
    # Don't bother subsetting the x and y variables of your plot.
    # plot() will automatically just plot those in the window.
    plot(temp$Time,temp$Open, 
    xlim=c(as.numeric(temp$Time[i]),as.numeric(temp$Time[i+150]))
    # Why are you setting the y limits dynamically? Shouldn't they be constant?
    # ,ylim=c(min(temp$Open[i:i+100]),max(tmep$Open[i:i+120])))
    Sys.sleep(.09)
}