Karl Ove Hufthammer
2006-May-11 14:06 UTC
[R] Conditional contour plots for estimated density functions using Lattice
Does anybody here have a suggestion for a clever way of creating contour plots for estimated bivariate density functions conditional on a factor? The contourplot function in the 'lattice' package only accepts data that are on the form 'z ~ x * y', not on the form 'x,y' or 'y~x'; otherwise I could probably have used the panel function to do the needed conversion. Here is my current, not very elegant, solution: estcontplot=function(x, y, grp, ...) { cest=matrix( nrow=0, ncol=4 ) for( i in levels(grp) ) { cest.gr=kde2d( x[grp==i], y[grp==i] ) cest.gr.lat=con2tr(cest.gr) cest.gr.lat=cbind(cest.gr.lat, i) cest=rbind(cest, cest.gr.lat) } contourplot( z ~ x * y | i, data=cest,...) } And here is a simple example of how it works: library(lattice) n=100 x <- y <- grp <- numeric() for(p in 1:4) { xx=rnorm(n)+p/3 yy=p*xx+rnorm(n)+p/3 x=c(x,xx) y=c(y,yy) grp=c(grp,rep(p,n)) } grp=factor(grp) xyplot(y~x|grp) estcontplot(x,y,grp) It has some problems if I add region=TRUE, and some of the contour lines are sometimes cut off, but this can easily be fixed by sending the range of the entire dataset to kde2d (with the 'lims' parameter) or perhaps by using scales="free". But surely there must be a smarter and more elegant way of drawing conditional contour plots using kernel density estimates? -- Karl Ove Hufthammer
Richard M. Heiberger
2006-May-12 14:46 UTC
[R] Conditional contour plots for estimated density functions using Lattice
Continuing with your example. Is this what you have in mind? Rich panel.estcontplot <- function(x, y, ..., col.points="black") { cest.gr=kde2d(x, y) cest.gr.lat=con2tr(cest.gr) panel.contourplot(cest.gr.lat$x, cest.gr.lat$y, cest.gr.lat$z, subscripts=seq(nrow(cest.gr.lat)), ...) panel.xyplot(x, y, ..., col=col.points) } xyplot(y ~ x | grp, panel=panel.estcontplot)