[R] test if something was plotted on pdf device

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Thu Sep 12 14:28:35 CEST 2019


On 12/09/2019 7:10 a.m., PIKAL Petr wrote:
> Dear all
> 
> Is there any simple way checking whether after calling pdf device something was plotted into it?
> 
> In interactive session I used
> 
> if (dev.cur()==1) plot(ecdf(rnorm(100))) else plot(ecdf(rnorm(100)), add=T, col=i)
> which enabled me to test if plot is open
> 
> But when I want to call eg. pdf("test.pdf") before cycle
> dev.cur()==1 is FALSE even when no plot is drawn and plot.new error comes.
> 
>> pdf("test.pdf")
> 
> if (dev.cur()==1) plot(ecdf(rnorm(100))) else plot(ecdf(rnorm(100)), add=T, col=i)
> 
> Error in segments(ti.l, y, ti.r, y, col = col.hor, lty = lty, lwd = lwd,  :
>    plot.new has not been called yet
> 

I don't know if this is reliable or not, but you could use code like this:

   f <- tempfile()
   pdf(f)
   blankPlot <- recordPlot()
   dev.off()
   unlink(f)

   pdf("test.pdf")

   ...  unknown operations ...

   if (dev.cur() == 1 || identical(recordPlot(), blankPlot))
     plot(ecdf(rnorm(100)))
   else
     plot(ecdf(rnorm(100)), add=TRUE, col=i)



Duncan Murdoch



More information about the R-help mailing list