R 语言散点图矩阵

浏览: 2880

散点图矩阵包含多种多副图片,因此含有更多的信息,特别是不同变量之间相关关系。本文介绍了graphics(pairs),car(spm),GGally(ggscatmat)和GGally(ggpairs)四种绘制散点图矩阵的函数。


① graphics 包 pairs 函数

data(trees)

panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)

{

  usr <- par("usr"); on.exit(par(usr))

  par(usr = c(0, 1, 0, 1))

  r <- abs(cor(x, y))

  txt <- format(c(r, 0.123456789), digits = digits)[1]

  txt <- paste0(prefix, txt)

  if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)

  text(0.5, 0.5, txt, cex = cex.cor * r)

}


panel.hist <- function(x, ...)

{

  usr <- par("usr"); on.exit(par(usr))

  par(usr = c(usr[1:2], 0, 1.5) )

  h <- hist(x, plot = FALSE)

  breaks <- h$breaks; nB <- length(breaks)

  y <- h$counts; y <- y/max(y)

  rect(breaks[-nB], 0, breaks[-1], y, col = "cyan", ...)

}


pairs(trees, 

      labels = c('树周长','树高','树体积'),

      lower.panel=panel.cor,

      upper.panel=panel.smooth,

      diag.panel=panel.hist,

      main = 'The Scatterplot Matrix of The Trees Data',

      pch = 21,

      bg = "orange",

      line.main=1.5,

      oma=c(2,2,3,2)

)


② car 包 spm 函数

#diagonal=c("density", "boxplot", "histogram", "oned", "qqplot", "none")

library(car)

data("trees")

spm(trees,

    diagonal='histogram',

    main='The Scatterplot Matrix of The Trees Data')




③GGally 包 ggscatmat 函数

library(GGally)

#ggscatmat(trees)

data("iris")

ggscatmat(iris, columns = 1:4,color = 'Species' )


④ GGally 包 ggpairs函数

library(ggplot2)

library(GGally)

data(tips,package="reshape")

#pairs(tips[,1:3])

pm1 <- ggpairs(

  tips[,c(1,3,4,2)],

  mapping = ggplot2::aes(color = sex,shape=sex,alpha = 0.4),

  upper = list(continuous = "cor", combo = "box", discrete = "facetbar"),

  lower = list(continuous = "points", combo = "facethist", discrete = "facetbar"),

  diag = list(continuous = "densityDiag", discrete = "barDiag")

)

pm1


data(iris)

pm2 <- ggpairs(

  iris[,c(1,2,5,3,4)],

  mapping = ggplot2::aes(color = Species,shape=Species,alpha = 0.4),

  upper = list(continuous = "density", combo = "box"),

  lower = list(continuous = "points", combo = "dot"),

  title = "Iris",

  axisLabels ="internal")

pm2


data(diamonds, package="ggplot2")

diamonds.samp <- diamonds[sample(1:dim(diamonds)[1], 200), ]

# Custom Example

pm3 <- ggpairs(

  diamonds.samp[, 1:5],

  mapping = ggplot2::aes(color = cut),

  upper = list(continuous = wrap("density", alpha = 0.5), combo = "box"),

  lower = list(continuous = wrap("smooth", alpha = 0.3), combo = wrap("dot", alpha = 0.4)),

  title = "Diamonds"

)

pm3




推荐 0
本文由 EasyCharts 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册