Plotting incrementally in R and not resetting

2019-05-10 10:25发布

问题:

What options (and package) would you use to incrementally plot the results of a calculation?

Imagine I want to plot the results of a computation that lasts for a very long time and I don't want to wait till the end to see some results. It won't be a good idea to plot every single point because it would be very slow to launch the plot command every time. I will plot every N points instead (saving them on a vector).

For example if I do it with the Fibonacci series, breaking the loop in two nested loops in order to plot the results every 10 iterations:

fibo=rep(0,112);fibo[1]=0;fibo[2]=1;
plot(fibo)              #to initialize 
for(ii in 0:10) {
  for(jj in 0:9) {
    fibo[ii*10+jj+3]=fibo[ii*10+jj+2]+fibo[ii*10+jj+1];
  }
plot(fibo)
}

But it doesn't keep the graph from the previous iteration. How I do this? This is not a good example because the numbers grow too quickly. And the plot initialization doesn't know the max y value in advance. Maybe it is better to use some other better graph package?

回答1:

Here's a simple example of how to do this by setting the points which should be plotted and only adding points when this criteria is met:

# set the frequency with which to plot points
plotfreq <- 10

# set the x and y limits of the graph
x.limits <- c(1,100)
y.limits <- c(0,100)

# initialise a vector and open a plot
result <- vector(mode="numeric",length=100)
plot(result,ylim=y.limits,xlim=x.limits,type="n")

# do the plotting
plot.iterations <- seq(plotfreq,length(result),by=plotfreq)
for (i in seq_along(result)) {
  result[i] <- result[i] + i

  # only plot if the data is at the specified interval
  if (i %in% plot.iterations) {
    points(i,result[i])
  }

}


标签: r plot updates