Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a matrix of scatterplots (pairs() equivalent) in ggplot2

People also ask

How do I plot multiple Scatterplots in R?

You can create a scatter plot in R with multiple variables, known as pairwise scatter plot or scatterplot matrix, with the pairs function. In addition, in case your dataset contains a factor variable, you can specify the variable in the col argument as follows to plot the groups with different color.


I keep wanting to do this, but plotmatrix is crap. Hadley recommends using the GGally package instead. It has a function, ggpairs that is a vastly improved pairs plot (lets you use non-continuous variables in your data frames). It plots different plots in each square, depending on the variable types:

library(GGally)
ggpairs(iris, aes(colour = Species, alpha = 0.4))

enter image description here


You might want to try plotmatrix:

  library(ggplot2)
  data(mtcars)
  plotmatrix(mtcars[,1:3])

to me mpg (first column in mtcars) should not be a factor. I haven't checked it, but there's no reason why it should be one. However I get a scatter plot :)


Note: For future reference, the plotmatrix() function has been replaced by the ggpairs() function from the GGally package as @naught101 suggests in another response below to this question.


If one wants to obtain a ggplot object (not ggmatrix as in case of ggpairs()), the solution is to melt the data twice, then ggplot with facetting. facet_wrap would be better than facet_grid in limiting the plotted area, given the scales = 'free' parameter is supplied.

require(ggplot2) 
require(dplyr)
require(tidyr)

gatherpairs <- function(data, ..., 
                        xkey = '.xkey', xvalue = '.xvalue',
                        ykey = '.ykey', yvalue = '.yvalue',
                        na.rm = FALSE, convert = FALSE, factor_key = FALSE) {
  vars <- quos(...)
  xkey <- enquo(xkey)
  xvalue <- enquo(xvalue)
  ykey <- enquo(ykey)
  yvalue <- enquo(yvalue)

  data %>% {
    cbind(gather(., key = !!xkey, value = !!xvalue, !!!vars,
                 na.rm = na.rm, convert = convert, factor_key = factor_key),
          select(., !!!vars)) 
  } %>% gather(., key = !!ykey, value = !!yvalue, !!!vars,
               na.rm = na.rm, convert = convert, factor_key = factor_key)
}

iris %>% 
  gatherpairs(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>% {
  ggplot(., aes(x = .xvalue, y = .yvalue, color = Species)) +
      geom_point() + 
      geom_smooth(method = 'lm') +
      facet_wrap(.xkey ~ .ykey, ncol = length(unique(.$.ykey)), scales = 'free', labeller = label_both) +
      scale_color_brewer(type = 'qual')
}

enter image description here


Try scatterPlotMatrix. It's very flexible and produces nice looking interactive charts.

library(scatterPlotMatrix)
scatterPlotMatrix(iris, zAxisDim = "Species")

enter image description here