[R] cannot create postscript files with trellis graphics inside a function

John Fox jfox at mcmaster.ca
Mon Apr 14 14:11:16 CEST 2003


Dear Faheem,

At 11:13 PM 4/13/2003 -0400, Faheem Mitha wrote:

>If I define
>
>foo <-function()
>{
>   x <- rnorm(500)
>   trellis.device(postscript, file="plot.ps")
>   densityplot(~x)
>   dev.off()
>  }
>
>and call foo() then plot.ps is just a blank plot. However, if I extract
>the lines inside foo and run them, ie.
>
>x <- rnorm(500)
>trellis.device(postscript, file="plot.ps")
>densityplot(~x)
>dev.off()
>
>then plot.ps is created without problems. The former method worked with
>the regular postscript() device, which I used to use all the time inside
>functions.
>
>I've never used lattice/trellis graphics before. Is this a bug or am I
>doing something wrong?

Lattice-graphics functions return objects rather than drawing plots as side 
effects. When you call a lattice function such as densityplot directly at 
the command plot, print is invoked implicitly and "prints" the plot. Within 
a function, you have to call print explicitly -- e.g., print(densityplot(~x)).

I hope that this helps,
  John
-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------



More information about the R-help mailing list