简体   繁体   English

与ggplot2的相关矩阵图

[英]Correlation matrix plot with ggplot2

I want to create a correlation matrix plot, ie a plot where each variable is plotted in a scatterplot against each other variable like with pairs() or splom() . 我想创建一个相关矩阵图,即一个图,其中每个变量在散点图中绘制,而不是像pairs()splom()那样相互splom() I want to do this with ggplot2. 我想用ggplot2做这个。 See here for examples . 请看这里的例子 The link mentions some code someone wrote for doing this in ggplot2, however, it is outdated and no longer works (even after you swap out the deprecated parts). 该链接提到了某人在ggplot2中编写的代码,但是,它已经过时且不再有效(即使在您更换了已弃用的部分之后)。

One could do this with a loop in a loop and then multiplot() , but there must be a better way. 可以通过循环中的循环然后使用multiplot()来做到这一点,但必须有更好的方法。 I tried melting the dataset to long, and copying the value and variable variables and then using facets. 我尝试将数据集熔化为long,然后复制值和变量,然后使用facet。 This almost gives you something correct. 这几乎给你一些正确的东西。

d = data.frame(x1=rnorm(100),
               x2=rnorm(100),
               x3=rnorm(100),
               x4=rnorm(100),
               x5=rnorm(100))
library(reshape2)
d = melt(d)
d$value2 = d$value
d$variable2 = d$variable

library(ggplot2)
ggplot(data=d, aes(x=value, y=value2)) +
  geom_point() +
  facet_grid(variable ~ variable2)

在此输入图像描述

This gets the general structure right, but only works for the plotting each variable against itself. 这使得一般结构正确,但仅适用于绘制每个变量对自己。 Is there some more clever way of doing this without resorting to 2 loops? 是否有一些更聪明的方法来做到这一点,而不诉诸2循环?

library(GGally)

set.seed(42)
d = data.frame(x1=rnorm(100),
               x2=rnorm(100),
               x3=rnorm(100),
               x4=rnorm(100),
               x5=rnorm(100))

# estimated density in diagonal
ggpairs(d)

在此输入图像描述

# blank
ggpairs(d, diag = list("continuous"="blank")

在此输入图像描述

Using PerformanceAnalytics library : 使用PerformanceAnalytics库:

library("PerformanceAnalytics")
chart.Correlation(df, histogram = T, pch= 19)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM