简体   繁体   中英

How to bind plot function to x11() in R?

I have a function that has an infinite loop, and inside it plots image object, and I create an x11() window and plot it there, but when I close the window, the function keeps running in the background. My R code can be seen below:

plotInfinite <- function()
{
  while(TRUE)
  {
    mat <- matrix(sample(0:1, 50*50, replace = TRUE), 50, 50)
    image(mat)
    Sys.sleep(0.1)
  }
}

x11()
plotInfinite()

Is it possible to somehow bind my function call to x11() window, such that when I close the window, also the function call terminates, ie breaks from the infinite loop?

You can define it in function like

plotInfinite <- function()
{
  dev=dev.cur() # get cur device name
  tt=TRUE
  while(tt==TRUE)
  {

    mat <- matrix(sample(0:1, 50*50, replace = TRUE), 50, 50)
    image(mat)
    Sys.sleep(0.1)
    if(dev!=dev.cur()){ tt=FALSE} #check if device changed
  }
}

then

x11()
plotInfinite()

will work before closed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM