[R] Plotting rows (or columns) from a matrix in different graphs, not using "par"

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jun 15 03:16:42 CEST 2005


On 6/14/05, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> On 6/14/05, Camarda, Carlo Giovanni <Camarda at demogr.mpg.de> wrote:
> > Dear R-users,
> > I would like to ask whether it's possible (for sure it would be), to
> > plot each rows (or columns) in different graphs and in the same figure
> > region without using the function "par" and then struggling around with
> > "axes" and labels etc.
> > Luckily, I would always have "rows + columns = even number" and the same
> > "ylim".
> >
> > The next one could be a sort of example on what I would like to avoid
> > plotting the rows of the matrix "mat":
> >
> > ########### EXAMPLE ######################
> > dat <- sort(runif(16, 1, 1000))
> > mat <- matrix(dat, ncol=4, byrow = T)
> > y   <- seq(1950, 1953)
> > par(mfrow=c(2,2))
> > plot(y, mat[1,], ylim=c(1,1000), axes=F, xlab="", ylab="simul.")
> > box()
> > axis(side=2, tick=T, labels=T)
> > axis(side=3, tick=T, labels=T)
> > plot(y, mat[2,], ylim=c(1,1000), axes=F, xlab="", ylab="")
> > box()
> > axis(side=3, tick=T, labels=T)
> > plot(y, mat[3,], ylim=c(1,1000), axes=F, xlab="years", ylab="simul.")
> > box()
> > axis(side=1, tick=T, labels=T)
> > axis(side=2, tick=T, labels=T)
> > plot(y, mat[4,], ylim=c(1,1000), axes=F, xlab="years", ylab="")
> > box()
> > axis(side=1, tick=T, labels=T)
> > ########### END EXAMPLE ########################
> >
> > Naturally something more compact would be even nicer.
> >
> 
> plot(ts(mat, start = 1950), nc = 2)
> 

I just looked at this again and noticed that it did not have
identical y axes.  I tried with ylim= too but plot.ts seemed
to ignore it.

Here is another solution that uses the zoo library.
Be sure to use zoo 1.0-1.  It uses the screens= argument of 
plot.zoo which was not available in earlier versions of zoo.

Instead of creating a ts series with 4 columns create a 
similar zoo series.  Append to that 4 dummy series all
with the same range.  Use the screens= argument
on plot.zoo to plot one real series and one dummy series
in each graph.  Use type = "l" to plot the real series
and type = "n" for the dummy series.  This causes the
real series to be plotted with lines and the dummy
series to be plotted invisibly yet still affect the
y axis range.    Note that we have used the fact that
mat is square so if the real mat is not square be sure
to modify this accordingly.

library(zoo) # 

n <- nrow(mat)
z <- zooreg(cbind(mat, max(mat) * diag(n)), start = 2000)
plot(z, screens = c(1:4, 1:4), type = rep(c("l","n"), each = 4), nc = 2)




More information about the R-help mailing list