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

Is it possible to build a matrix of scatterplots with ggplot2 using ggplot nice features such as displaying additional factors in color, shape, etc. and adding smoother?

I am thinking of something like the base pairs function.

+78
r ggplot2
Sep 17 '10 at 12:28
source share
3 answers

You might want to try plotmatrix:

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

me mpg (first column in mtcars) should not be a factor. I have not tested it, but there is no reason why it should be alone. 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 offers in another answer below to this question.

+21
Sep 17 '10 at 12:36
source share

I want to do this all the time, but the storyteller is shit. Hadley recommends the GGally package instead . It has a ggpairs function, which is a significantly improved pair plot (allows you to use continuous variables in your frames). It displays different graphs in each square, depending on the types of variables:

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

enter image description here

+167
Aug 21 2018-12-12T00:
source share

If you want to get the ggplot object (not ggmatrix , as in the case of ggpairs() ), the solution is to melt the data twice and then ggplot with the facet. facet_wrap would be better than facet_grid in limiting the plot area if scales = 'free' .

 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

+1
Dec 09 '17 at 17:18
source share