[R] redirect plot device automatically

jim holtman jholtman at gmail.com
Fri Jan 4 02:59:33 CET 2008

I have used a function like this to capture the output on the terminal
to a file:

f.plot <- local({   # this will make PlotNumber 'local' (private)
    PlotNumber <- 1 # initialize the plot number (known just to this function)
    return(function(){ # returns the 'function' as the result
      file=fileName <- sprintf("%sws.%03d.wmf", RWS_TEMP, PlotNumber),
         # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         # the fileName uses RWS_TEMP to determine where to store the plots
        width=10, height=7)
      cat(fileName, "\n")      PlotNumber <<- PlotNumber + 1  #
increment for next plot
      invisible(dev.off())  # close the file and don't print return value

This creates a function 'f.plot' that is used as follows: anytime that
I have created a plot, I just call f.plot to make a copy.  It
increments the file name automatically:

plot(Time, User, main='plot(Time, User)')  # default is 'points'
plot(Time, User, type="l",
    main='plot(Time, User, type="l")')  # line plot

I assume that I will work for 'png' files.  If you don't want output
created, just do

f.plot <- function() invisible(NULL)

On Jan 3, 2008 7:47 PM, Milton Cezar Ribeiro <milton_ruser at yahoo.com.br> wrote:
> Dear all,
> Every time that I need to generate I plot output as figure I use something like
> png("myoutput.png")
> plot(rnorm(100)*1.0,col=4)
> points(rnorm(100)*0.5,col=2,pch=0)
> dev.off()
> But now I need to generate a lot of outputs and it could not be done in a for looping where I can change the names. So I would like to know if is there a way of I automatically redirect the output from my screen to a png file, and the name of the generated files follow a prefix and a numeration like myoutput001.png  / myoutput002.png....
> Byt the way, my example is with plot, but I will use plot(x), image(x), points(x), lines(x) etc.
> Any idea?
> Kind regards
> Miltinho
> Brazil
>  para armazenamento!
>        [[alternative HTML version deleted]]
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

More information about the R-help mailing list