1

How to get graph for each column of data.frame within one plot with loop? Must be easy just can't figure it out.

Sample data:

rdata <- data.frame(y=rnorm(1000,2,2),v1=rnorm(1000,1,1),v2=rnorm(1000,3,3),
                    v3=rnorm(1000,4,4),v4=rnorm(1000,5,5))

What I have tried?

library(lattice)

p <- par(mfrow=c(2,2))
for(i in 2:5){
w <- xyplot(y~rdata[,i],rdata)
print(w)
}
par(p)
Maximilian
  • 4,177
  • 7
  • 46
  • 85

2 Answers2

3

If you don't have to use lattice you can just use base plot instead and it should work as you want.

p <- par(mfrow=c(2,2))
for(i in 2:5){
    plot(y~rdata[,i],rdata)
}
par(p)

enter image description here

If you want to use lattice look this answer. Lattice ignores par, so you have to do some more work to achieve what you want.

Community
  • 1
  • 1
alko989
  • 7,688
  • 5
  • 39
  • 62
  • Thanks, yes I know it works with `plot` but I have done so far everything in lattice so can't change now to different layout/setup. I will look into your reference. Thanks! – Maximilian Jul 11 '14 at 12:36
3

Inorder to easily arrange a bunch of lattice plots, I like to use the helper function print.plotlist. It has a layout= parameter that acts like the layout() function for base graphics. For example, you could call

rdata <- data.frame(y=rnorm(1000,2,2),v1=rnorm(1000,1,1),v2=rnorm(1000,3,3),
                    v3=rnorm(1000,4,4),v4=rnorm(1000,5,5))

library(lattice)
plots<-lapply(2:5, function(i) {xyplot(y~rdata[,i],rdata)})
print.plotlist(plots, layout=matrix(1:4, ncol=2))

to get

enter image description here

Otherwise you normally use a split= parameter to the print statement to place a plot in a subsection of the device. For example, you could also do

print(plots[[1]], split=c(1,1,2,2), more=T)
print(plots[[2]], split=c(1,2,2,2), more=T)
print(plots[[3]], split=c(2,1,2,2), more=T)
print(plots[[4]], split=c(2,2,2,2))
MrFlick
  • 195,160
  • 17
  • 277
  • 295