[R] Splitting device for ggplots?

Jim Price price_ja at hotmail.com
Mon Nov 3 19:34:58 CET 2008


You could write a function to get rid of a lot of the grunt work; for example
(this using lattice instead of ggplot, but should be pretty much the same):


library(lattice)
library(grid)

graphics.off()


myPlot1 <- xyplot(1 ~ 1 | 1)
myPlot2 <- xyplot(2 ~ 2 | 2)
myPlot3 <- xyplot(3 ~ 3 | 3)
myPlot4 <- xyplot(4 ~ 4 | 4)
myPlot5 <- xyplot(5 ~ 5 | 5)
myPlot6 <- xyplot(6 ~ 6 | 6)


grid.mfrow <- function(dims, ...)
{
	if(!is.numeric(dims) | length(dims) != 2)
		stop('Entry must be length-2 numeric vector')

	plots <- list(...)

	for(i in seq(dims[1]))
	{
		for(j in seq(dims[2]))
		{
			pushViewport(viewport(
				x = (j-1) / dims[2], 
				y = (1 - (i-1) / dims[1]),
				width = 1 / dims[2],
				height = 1 / dims[1],
				just = c('left','top')
			))
			print(plots[[dims[2] * (i - 1) + j]], newpage = F)
			upViewport()
		}
	}
}



grid.mfrow(c(2,3), myPlot1, myPlot2, myPlot3, myPlot4, myPlot5, myPlot6)


Jim Price
Cardiome Pharma Corp.


Spinu Vitalie wrote:
> 
> Thanks Baptiste and Hadley,
> 
> That viewports mechanism is indeed extremely versatile when it comes to  
> publication or designing new plot functions. But for interactive analysis  
> all these "pushing" and "popping" is just a way too much code - for each  
> plot at least two additional grid functions, one plot variable and  
> explicit print with location are required. For just 10 plots it's already  
> a page or so of redundant code.
> 
> It would be really wonderful  if classic mfrow or layout mechanism were  
> implemented for lattice and ggplots.
> 
> The simplest trick I could think of for myself is to overwrite the print  
> method for ggplots and to append execution of a custom function  
> (gg.postplot say) which would do "popping" and "pushing" into next sell in  
> grid.layout.
> 
> Vitalie.
> 
> On Sat, 01 Nov 2008 15:26:36 +0100, hadley wickham <h.wickham at gmail.com>  
> wrote:
> 
>> On Sat, Nov 1, 2008 at 5:13 AM, baptiste auguie <ba208 at exeter.ac.uk>  
>> wrote:
>>> Hi,
>>>
>>> I believe you can apply the same procedure as described in Paul  
>>> Murrell's "R
>>> graphics" book for arranging lattice plots.
>>
>> Yup, and see also http://had.co.nz/ggplot2/book/grid.pdf
>>
>> Hadley
>>
>>
> 
> ______________________________________________
> 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.
> 
> 

-- 
View this message in context: http://www.nabble.com/Splitting-device-for-ggplots--tp20278701p20308073.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list