R: Loop pairs of columns in a dataframe

Is it possible to plot pairs of columns in a single plot with a loop? For example, if I have a data frame of time series with 10 columns (x1, x2.. x10), I would like to create 5 plots: 1st plot will display x1 and x2, the 2nd plot would display x3 and x4 and so on.

Any plotting method would be useful, (zoo, lattice, ggplot2).

I got stuck at creating a loop to plot a single variable:


x<- data.frame(replicate(10,rnorm(10, mean = 0, sd = 1)))
cols <- seq(1,10) 

z <- read.zoo(x)

for (i in cols) {
plot(z[,i], screen = 1)

Thanks in advance.


How about this with ggplot2 and reshape2:

ggplot(m)+geom_line(aes(x=Var1,y=value,group=Var2,color=factor(Var2)))+facet_wrap(~ facet)

It can be done in a single line without a loop like this where the col argument specifies that the odd series are black and the even are red. Note that z in the question has 9 columns (since the first column in x is the time index) so we have used a 10 column z below instead which was likely what was intended.

# test data
set.seed(123); z <- zoo(matrix(rnorm(250), 25)); colnames(z) <- make.names(1:10)

plot(z, screen = rep(colnames(z)[c(TRUE, FALSE)], each = 2), col = 1:2)

The output is shown below. To produce a single column add the argument nc=1 or to produce a lattice plot replace plot with xyplot.

ADDED: lattice solution.

like this? Although I am not clear how you want to plot it.

for (i in seq(1,10,by=2)){


Need Your Help

Getting accurate referrals from arbitrary sites analytics.js

google-analytics cross-domain google-analytics-api analytics.js

Working on a web app where at step 2 the user leaves to her domain and comes back. The domain she leaves to is dynamically entered into our form (this step is required for an OAuth token flow).

Event-sourcing with akka-persistance: growing state as list?

scala akka cqrs event-sourcing akka-persistence

I am designing a backend using CQRS + Event sourcing, using Akka + Scala. I am not sure about how to handle a growing state. For instance, I will have a growing list of users. To my understanding, ...