Is there any R package/method/function that provides the functionality to plot a matrix of scatterplots as here (scatterplot.matrix
function of the car
package, found here) AND to plot x and y errorbars as has been asked and answered here.
An example:
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))
require(ggplot2)
ggplot(data = df, aes(x = X, y = Y)) + geom_point() +
geom_errorbar(aes(ymin = Y-errY, ymax = Y+errY)) +
geom_errorbarh(aes(xmin = X-errX, xmax = X+errX)) + theme_bw()
produces the following plot (X vs Y with errorbars):
while
library(car)
spm(~X+Y+Z, data=df)
produces a scatterplot matrix such as this:
Now my expected output would be such a matrix of scatterplots (any other package than car
will be fine as well) where I can also display errorbars. (Note that not all of my variables have errors, e.g. Z
does not). Also the fitting etc that is done here by the spm
function is a nice gimmick but not necessary for my means.
Data
Code
Explanation
First, you have to transform your data in a way, such that
ggplot2
likes it. That is, one column each for your x- and y-axis respectively plus one column each for the error bars.What I used here, is function
permutations
fromlibrary(gtools)
, which returns (in this case) all 2 element permutations. For each of these permutations, I select the corresponding column from the original data set and add the related error columns (if existing). If the column names follow a certain pattern for value and error bar columns, you can useregex
to determine these automatically like in:Finally, I add the columns
var1
andvar2
describing which variables were selected:Having the data transformed this way makes it rather easy to generate the scatter plot matrix. With this approach it is also possible to modify the diagonal panel as shown in the follwing example:
Plot