Plotting during a loop in RStudio

Calling Sys.sleep(0) should cause the plot to draw. Unlike the X11 solution, this will work on server versions of RStudio as well.

(I was surprised that dev.flush() did not give the result you were hoping for, that might be a bug.)


Following up on @JoeCheng's answer and @RGuy's comment on that answer: as I worked out with the RStudio folks, the problem seems to primarily arise when there is too much plotting going on in too short a timespan. The solution is twofold:

  • Sys.sleep(0) helps force an update to the plotting window.
  • Plotting updates every Wth loop rather than every loop.

For instance, on my computer (i7, RStudio Server), the following code does not update until the loop completes:

N <- 1000
x <- rep(NA,N)
plot(c(0,1)~c(0,N), col=NA)
for(i in seq(N)) {
  Sys.sleep(.01)
  x[i] <- runif(1)
  iseq <- seq(i-99,i)
  points( x[i]~i )
  Sys.sleep(0)
}

The following code updates in real-time, despite having the same number of points to be plotted:

N <- 1000
x <- rep(NA,N)
plot(c(0,1)~c(0,N), col=NA)
for(i in seq(N)) {
  Sys.sleep(.01)
  x[i] <- runif(1)
  iseq <- seq(i-99,i)
  if(i%%100==0) {
    points( x[iseq]~iseq )
    Sys.sleep(0)
  }
}

In other words, it's the number of calls the plot that seems to matter, not the amount of data to be plotted.


One thing you can do is open a x11 window and plot in there:

x11()
Plotz()

That should work the same as running it in terminal.

Tags:

Plot

R

Rstudio