Data
set.seed(123) df <- data.frame(X = rnorm(10), errX = rnorm(10)*0.1, Y = rnorm(10), errY = rnorm(10)*0.2, Z = rnorm(10))
the code
library(ggplot2) library(gtools) valCols <- c("X", "Y", "Z") errCols <- setNames(c("errX", "errY", NA), valCols) combn <- permutations(length(valCols), 2, valCols) mdf <- do.call(rbind, apply(combn, 1, function(ind) { df[["NA.Column"]] <- NA errC <- errCols[ind] errC[is.na(errC)] <- "NA.Column" vals <- setNames(data.frame(df[, ind]), paste0("val", seq_along(ind))) errs <- setNames(data.frame(df[, errC]), paste0("err", seq_along(errC))) ret <- cbind(vals, errs) ret$var1 <- factor(ind[1], levels = valCols) ret$var2 <- factor(ind[2], levels = valCols) ret })) (p <- ggplot(mdf, aes(x = val1, y = val2, ymin = val2 - err2, ymax = val2 + err2, xmin = val1 - err1, xmax = val1 + err1)) + geom_point() + geom_errorbar() + geom_errorbarh() + facet_grid(var1 ~ var2, drop = FALSE))
Explanation
First, you need to convert your data in such a way that ggplot2 likes it. That is, one column for your x and y axis, respectively, plus one column for error bars.
What I used here is the permutations from library(gtools) , which returns (in this case) all 2 elementary permutations. For each of these permutations, I select the corresponding column from the source dataset and add the corresponding error columns (if they exist). If the column names match a specific pattern of column columns of value columns and column columns of error columns, you can use regex to determine them automatically, as in:
valCols <- names(df)[grepl("^[AZ]$", names(df))]
Finally, I add the var1 and var2 columns describing which variables were selected:
head(mdf) # val1 val2 err1 err2 var1 var2 # 1 -0.56047565 -1.0678237 0.12240818 0.08529284 XY # 2 -0.23017749 -0.2179749 0.03598138 -0.05901430 XY # 3 1.55870831 -1.0260044 0.04007715 0.17902513 XY # 4 0.07050839 -0.7288912 0.01106827 0.17562670 XY # 5 0.12928774 -0.6250393 -0.05558411 0.16431622 XY # 6 1.71506499 -1.6866933 0.17869131 0.13772805 XY
Having transformed data thus simplifies the creation of a scatter plot matrix. With this approach, it is also possible to change the diagonal panel, as shown in the following example:
p + geom_text(aes(ymin = NULL, ymax = NULL, xmin = NULL, xmax = NULL), label = "X", data = data.frame(var1 = "X", var2 = "X", val1 = 0, val2 = 0))
Earth

