Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting during a loop in RStudio

Tags:

plot

r

rstudio

I am implementing a solution to the Traveling Salesman Problem (TSP) in R (simulated Annealing) and I want to output the current best path periodically. I have searched quite a bit for how to output plots during a for loop and have thus far failed.

I use RStudio, and want to see the graphs as they are generated. If you have ever watched TSP solvers do their thing, you will understand how cool it is to watch. Here is a sample of the graphics output I want to see http://www.staff.science.uu.nl/~beuke106/anneal/anneal.html

I don't think that the memory usage will be a problem (during about 500,000 iterations, I am only expecting 50-100 plots). Here is a sample function, where we would expect to see 10 different plots during the time the function runs:

Plotz <- function(iter = 1000000, interval = 100000) {
  x <- 1:10
  for(i in 1:iter){
    y <- runif(10)
    if(i %% interval == 0) {
      plot(x, y)
    }
  }
  return(c(x, y))
}
Plotz()

When I run this, all I see is the final plot produced (in RStudio). How can I see the plots as they're generated?

Also: I am on Ubuntu (whatever the newest stable release is). Don't know if that is relevant.

Thank you everyone in advance.

EDIT: Per Captain Murphy's suggestion, I tried running this in the Linux terminal, and the graphics appeared. I still think the question of "How to do this in RStudio?" Is still relevant, however. It's such a good program, so maybe someone has an idea of what could be done to get this to work?

EDIT2: As Thilo stated, this is a known bug in Rstudio. If anyone has any other ideas to solve this without the software itself being fixed, then there is still something to discuss. Otherwise, consider this question solved.

like image 291
Rguy Avatar asked Jan 07 '12 20:01

Rguy


People also ask

Does Ggplot work in for loop?

ggplot does not work if it is inside a for loop although it works outside of it [duplicate] New! Save questions or answers and organize your favorite content. Learn more.

Can you plot a function in R?

The most used plotting function in R programming is the plot() function. It is a generic function, meaning, it has many methods which are called according to the type of object passed to plot() . In the simplest case, we can pass in a vector and we will get a scatter plot of magnitude vs index.


1 Answers

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.)

like image 105
Joe Cheng Avatar answered Sep 23 '22 19:09

Joe Cheng