Skip to content
Prev 276479 / 398506 Next

Correlation between matrices

Hi:

I don't think you want to keep these objects separate; it's better to
combine everything into a data frame. Here's a variation of your
example - the x variable ends up being a mouse, but you may have
another variable that's more appropriate to plot so take this as a
starting point. One plot uses the ggplot2 package, the other uses the
lattice and latticeExtra packages.

library('ggplot2')
regions = c('cortex', 'hippocampus', 'brain_stem', 'mid_brain',
            'cerebellum')
mice = paste('mouse', 1:5, sep='')
elem <- c('Cu', 'Fe', 'Zn', 'Ca', 'Enzyme')

# Generate a data frame from the combinations of
# mice, regions and elem:
d <- data.frame(expand.grid(mice = mice, regions = regions,
                            elem = elem), y = rnorm(125))
# Create a numeric version of mice
d$mouse <- as.numeric(d$mice)

# A function to return regression coefficients
coefun <- function(df) coef(lm(y ~ mouse), data = df)
# Apply to all regions * elem combinations
coefs <- ddply(d, .(regions, elem), coefun)
names(coefs) <- c('regions', 'elem', 'b0', 'b1')

# Generate the plot using package ggplot2:
ggplot(d, aes(x = mouse, y = y)) +
   geom_point(size = 2.5) +
   geom_abline(data = coefs, aes(intercept = b0, slope = b1),
                             size = 1) +
   facet_grid(elem ~ regions)

# Same plot in lattice:
library('lattice')
library('latticeExtra')
p <- xyplot(y ~ mouse | elem + regions, data = d, type = c('p', 'r'),
         layout = c(5, 5))


HTH,
Dennis
On Sat, Nov 5, 2011 at 10:49 AM, Kaiyin Zhong <kindlychung at gmail.com> wrote: