Mark Heckmann
2008-Dec-05 16:38 UTC
[R] Problems with lattice-histograms or png within loops
Dear R-users, I have a question concerning the use of lattice plots within for-loops. I want to create a png file containing a lattice histogram which works out fine (part 1). When I loop the whole code, the graphic file does not contain anything (part 2). I can fix it by wrapping the histogram function into a print command (part 3). Why is that so? Why can I not loop it directly? TIA, Mark attach(iris) ### part 1 png(filename = "graphic_1.png") histogram( ~ Sepal.Length | Species, data = iris) dev.off() ### part 2 for (i in c(1)) { png(filename = "graphic_2.png") histogram( ~ Sepal.Length | Species, data = iris) dev.off() } ### part 3 for (i in c(1)) { png(filename = "graphic_3.png") print(histogram( ~ Sepal.Length | Species, data = iris)) dev.off() }
Richard.Cotton at hsl.gov.uk
2008-Dec-05 17:05 UTC
[R] Problems with lattice-histograms or png within loops
> I have a question concerning the use of lattice plots within for-loops. > I want to create a png file containing a lattice histogram which worksout> fine (part 1). > When I loop the whole code, the graphic file does not contain anything(part> 2). > I can fix it by wrapping the histogram function into a print command(part> 3). > Why is that so? Why can I not loop it directly? > > TIA, > Mark > > attach(iris) > > ### part 1 > png(filename = "graphic_1.png") > histogram( ~ Sepal.Length | Species, data = iris) > dev.off() > > ### part 2 > for (i in c(1)) > { > png(filename = "graphic_2.png") > histogram( ~ Sepal.Length | Species, data = iris) > dev.off() > } > > ### part 3 > for (i in c(1)) > { > png(filename = "graphic_3.png") > print(histogram( ~ Sepal.Length | Species, data = iris)) > dev.off() > }This is FAQ 7.22: http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f The help page on ?histogram also mentions that the function returns "an object of class 'trellis'" and "the 'print' method (usually called by default) will plot it on an appropriate plotting device" It's a good idea to get into the habit of calling print any time you create a lattice graph. If you reorder your code like h1 <- histogram( ~ Sepal.Length | Species, data = iris) png(filename = "graphic_h1.png") print(h1) dev.off() then you won't end up with an open device if drawing the plot fails. Regards, Richie. Mathematical Sciences Unit HSL ------------------------------------------------------------------------ ATTENTION: This message contains privileged and confidential inform...{{dropped:20}}