代码之家  ›  专栏  ›  技术社区  ›  Karsten W.

在ggplot2中创建散点图矩阵(pairs()等效)

  •  100
  • Karsten W.  · 技术社区  · 14 年前

    是否有可能绘制散点图矩阵 ggplot2 ,使用 ggplot 的不错的功能,如映射额外的因素,颜色,形状等,并增加平滑?

    我在考虑类似于 base 功能 pairs

    3 回复  |  直到 10 年前
        1
  •  40
  •   Community CDub    8 年前

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


    注: plotmatrix() 函数已被替换为 ggpairs() GGally 按照@101的建议打包 in another response below 关于这个问题。

        2
  •  237
  •   naught101    8 年前

    我一直想这么做,但阴谋矩阵是垃圾。哈德利 recommends 使用 GGally package 相反。它有一个功能, ggpairs 这是一个大大改进的pairs图(允许在数据帧中使用非连续变量)。它在每个正方形中绘制不同的绘图,具体取决于变量类型:

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

    enter image description here

        3
  •  18
  •   mjktfw    7 年前

    ggplot ggmatrix 例如 ggpairs() ),解决方法是将数据融化两次,然后 GG图 facet_wrap facet_grid 在限制绘图区域时,给定 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