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)

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!
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))

1 Comment

I have figured it out in meantime but this is different approach I can learn from. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.