0

Possible Duplicate:
Generate multiple graphics from within an R function

I'm trying to store all the plot from all the variables in my data with histogram from the package lattice. When I run directly, it works but if I use a function don't create the figures. My function is:

plotHistByGroups<-function(data, res)
{
   jpeg("plots/histBy%03d.jpg", quality=100)
   finalres<-as.factor(res)
   names<-colnames(data)
   library(lattice)
   for( i in 1: length(data))
   {
     title<-paste(names[i], "~")
     title<-paste(title, length(levels(finalres)))
     title<-paste(title, "clusters")
     histogram(~data[,i] | finalres, data, xlab=names[i], main=title)    
   }
   dev.off()
}

When I call the function, I only get one empty figure. But, I obtain all the figures If I directly run:

jpeg("plots/histBy%03d.jpg", quality=100)
histogram(~data[,1] | finalres, data, xlab=names[1], main=title)    
histogram(~data[,2] | finalres, data, xlab=names[2], main=title)    
histogram(~data[,3] | finalres, data, xlab=names[3], main=title)    
...
dev.off()

Bea

Community
  • 1
  • 1
  • PS are you sure you want to save as JPEG? Vector formats are best if possible, but even if you need a bitmap format, PNG is usually best for data graphics (JPEG is intended for photos and other pictures with gradual gradation in color) – Ben Bolker Sep 20 '12 at 16:11
  • I've never had problems with high res PNG's being of too low quality. All journals have accepted my PNG's without any problem. – Paul Hiemstra Sep 20 '12 at 19:02
  • Possible duplicates [here](http://stackoverflow.com/questions/7981507/lattice-plots-not-working-inside-a-function), [here](http://stackoverflow.com/questions/5450257/graph-does-not-show-after-type-lattice-command) and [here](http://stackoverflow.com/questions/6783120/r-package-lattice-wont-plot-if-run-using-source). – joran Sep 22 '12 at 21:04

1 Answers1

2

You need to wrap this in a print(histogram(...)) and yes, this is question 7.22 in the R FAQ:

7.22 Why do lattice/trellis graphics not work?

The most likely reason is that you forgot to tell R to display the graph. Lattice functions such as xyplot() create a graph object, but do not display it (the same is true of ggplot2 graphics, and Trellis graphics in S-PLUS). The print() method for the graph object produces the actual display. When you use these functions interactively at the command line, the result is automatically printed, but in source() or inside your own functions you will need an explicit print() statement.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • 4
    http://stackoverflow.com/questions/4811106/cant-print-to-pdf-ggplot-charts , http://stackoverflow.com/questions/9541145/r-lattice-plots-and-postscript , http://stackoverflow.com/questions/8188375/why-is-ggplot-not-plotting-multiple-windows-in-r , http://stackoverflow.com/questions/2547306/generate-multiple-graphics-from-within-an-r-function ... – Ben Bolker Sep 20 '12 at 16:09