Question

I'm trying to create a scatterplot matrix where the x and y variables of the matrix are different (as opposed to pairs() which use the same variables for both x and y axes).

Currently I'm using pairs2() function from the TeachingDemos library, but would like to have more control to its appearance and am thinking of replicating it using ggplot2. Is there something equivalent in ggplot2? Or how best should I produce a similar scatterplot matrix if I don't want to use the pairs2() function?

Not sure if I need to post sample code, here it is anyway

library(TeachingDemos)
a <- matrix(runif(1:10), ncol = 2)
b <- matrix(sample(1:10), ncol = 2)
pairs2(a,b)

Edit:

to clarify, a and b are both matrixes of 2 different variables each. May be clearer with the following sample code instead

library(TeachingDemos)
a <- matrix(runif(1:10), ncol = 2)
b <- matrix(sample(1:10), ncol = 2)
colnames(a) <- c("Ratio of correct answer", "Ratio of time spent")
colnames(b) <- c("Hours spent per study session", "Frequency of study per week")
pairs2(a,b)

Thanks Henrik for the suggestion. Apologies on uncear descriptions, a learning noob here, all suggestions welcome.

Was it helpful?

Solution

As is often the case with ggplot2, the hard part is getting the data into the correct form. In this case we want to collapse the two x-variable columns into one, collapse the two y-variable columns into one, and add indicators that denote which x and y variable each value comes from:

library(reshape2)
library(ggplot2)    
dat <- data.frame(a, b)
    names(dat) <- c("x_1", "x_2", "y_1", "y_2")
    dat.m <- melt(dat, measure.vars = c("x_1", "x_2"), variable.name = "x_var", value.name = "x")
    dat.m <- melt(dat.m, measure.vars = c("y_1", "y_2"), variable.name = "y_var", value.name = "y")

Now that the data is in the form expected by ggplot2, constructing the actual graphic is easy:

ggplot(dat.m, aes(x=x, y=y)) +
    geom_point()+
    facet_grid(y_var ~ x_var, scales="free")

enter image description here

EDIT: An updated version corresponding to your new example is

library(reshape2)
library(ggplot2)    

dat <- data.frame(a, b, check.names = FALSE)

dat.m <- melt(dat,
              measure.vars = colnames(a),
              variable.name = "x_var",
              value.name = "Ratio")

dat.m <- melt(dat.m,
              measure.vars = colnames(b),
              variable.name = "y_var",
              value.name = "Study")

ggplot(dat.m, aes(x=Ratio, y=Study)) +
    geom_point()+
    facet_grid(y_var ~ x_var, scales="free")

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top