关于r:在ggplot2中创建散点图矩阵(pairs()等效)

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

是否可以使用ggplot的精美功能(例如将其他因子映射到颜色,形状等并添加更平滑的图像),用ggplot2绘制散布图矩阵?

我正在考虑类似于base函数pairs的内容。


我一直想这样做,但plotmatrix很糟糕。 Hadley建议改用GGally软件包。它具有ggpairs函数,这是一个大大改进的对图(让您在数据帧中使用非连续变量)。它根据变量类型在每个正方形中绘制不同的图:

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

enter image description here


您可能想尝试一下plotmatrix:

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

对我而言,mpg(mtcars的第一列)不应成为一个因素。我没有检查它,但是没有理由为什么它应该是一个。但是我得到了一个散点图:)

注意:为将来参考,已将plotmatrix()函数替换为GGally包中的ggpairs()函数,如@ naught101在下面对此问题的另一个答复中所建议的。


如果要获取一个ggplot对象(而不是像ggpairs()一样是ggmatrix),则解决方案是将数据融化两次,然后对ggplot进行分面。在提供scales = 'free'参数的情况下,在限制绘制区域方面,facet_wrapfacet_grid更好。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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