首页 文章

在ggplot2中创建一个散点图矩阵(pair()等价物)

提问于
浏览
96

是否可以使用 ggplot2 绘制散点图矩阵,使用 ggplot 的漂亮功能,例如将其他因素映射到颜色,形状等,并添加更平滑的?

我正在考虑类似于 base 函数 pairs 的东西 .

3 回答

  • 198

    您可能想尝试plotmatrix:

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

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


    Note: 为了将来参考, plotmatrix() 函数已被 GGally 函数替换为 ggpairs() 函数,因为@ naught101建议in another response below来回答这个问题 .

  • 25

    我一直想做这个,但plotmatrix是废话 . Hadley recommends使用GGally package代替 . 它有一个函数,ggpairs是一个极大改进的对图(允许你在数据框中使用非连续变量) . 它根据变量类型绘制每个方块中的不同图:

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

    enter image description here

  • 7

    如果想要获得一个 ggplot 对象(不是 ggmatrix ,如 ggpairs() 的情况),解决方案是将数据融合两次,然后使用facetting进行 ggplot . 在给定 scales = 'free' 参数的情况下, facet_wrap 在限制绘制区域方面优于 facet_grid .

    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

相关问题