Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add a general grid to a lattice xy.plot

Tags:

r

lattice

This question explains how to add grids at specific points for a lattice plot (i.e. the equivalent of two abline()'s for a normal plot). My problem is that when i try to add a regular grid (the equivalent of a call to grid() for a normal plot)...the content of the plots... disappear. Here is an example:

B<-cbind(rnorm(100),rnorm(100), floor(runif(100,1,7)), floor(runif(100,1,3)), 
           floor(runif(100,1,4)))
colnames(B)<-c("yval","xval","gval","p","cr")
B<-as.data.frame(B)
xyplot(B$yval~B$xval|B$p*B$cr,group=B$gval,main="Scatterplots by Cylinders and Gears", 
           ylab="Miles per Gallon", xlab="Car Weight",type="l",lwd=5,
           panel=function(x,y){panel.grid()})

if you remove the last option (i.e. panel=function(x,y){panel.grid()}) then i see the data-lines, but not the grid(). Is there a way to have both the grid and the data-lines

thanks in advance,

like image 235
user189035 Avatar asked Mar 14 '12 10:03

user189035


1 Answers

Try this:

xyplot(yval ~ xval | p*cr, data=B, group=gval, type=c("l","g"), lwd=5, 
       main="Scatterplots by Cylinders and Gears",
       ylab="Miles per Gallon", xlab="Car Weight")

I have simplified a little bit your syntax because you can use variable names from you data.frame if you the data= argument. The key is to use type=c("l","g"), which means lines + grid, and is equivalent to a panel function that would looks like

panel=function(...) {
  panel.xyplot(...)
  panel.grid()
}

In your case, this is because you forgot to add a panel.xyplot() that no points or line were drawn. If you want a different grid, you can use the above code and customize the call to panel.grid().

like image 113
chl Avatar answered Nov 04 '22 01:11

chl