# [R] Conditional contour plots for estimated density functions using Lattice

Karl Ove Hufthammer karloh at mi.uib.no
Thu May 11 16:06:16 CEST 2006

```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

```