[R] Lattice: multiple data sets on same plot

Joel Thomas joeliol at gmail.com
Wed Dec 2 23:44:46 CET 2009


Hi,
I have two data sets; one is a population and the other a sample of
that population. I am trying to plot both on the same trellis display.

# Example data set with two numerical attributes and two categorical
pop <- data.frame(var1=rnorm(2000, 2000, 500), var2=rnorm(2000, 2000, 500))

cat<-(runif(2000)<=.5)+0
for(i in 1:length(cat)){
   if(cat[i] == 0){
      pop[i,"cat1"] = "this"
   }
   else{
      pop[i,"cat1"] = "that"
   }
}
cat<-(runif(2000)<=.5)+0
for(i in 1:length(cat)){
   if(cat[i] == 0){
      pop[i,"cat2"] = "here"
   }
   else{
      pop[i,"cat2"] = "there"
   }
}

#Extract sample
sam <- pop[sample(1:2000,50),]

#Combine data sets
x <- make.groups(pop, sam)

#Create trellis display
densityplot(~var1 + var2 | cat1 * cat2, data=x, groups=which,
plot.points=FALSE, auto.key=list(columns=2))


This does not produce what I want. I would like four density plots in
each panel; var1 and var2 from the sample data as solid lines and var1
and var2 from the population data as dotted lines with matching
colours.

densityplot(~ var1 + var2 | cat1 * cat2, data=x, groups=which,
      panel=panel.superpose,
      panel.groups = function(x, y,...){
        panel.densityplot(x, ...)
        })

... gives the same result.

I've read "The panel function demystified" section of the book many
times and still find the panel function mystifying. Could someone
please explain how to do this and also how it works. Thankyou




More information about the R-help mailing list