Correlation matrix plot with ggplot2

蓝咒 提交于 2019-12-20 21:54:09

问题


I want to create a correlation matrix plot, i.e. a plot where each variable is plotted in a scatterplot against each other variable like with pairs() or splom(). I want to do this with 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).

One could do this with a loop in a loop and then multiplot(), but there must be a better way. I tried melting the dataset to long, and copying the value and variable variables and then using facets. 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?


回答1:


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")




回答2:


Using PerformanceAnalytics library :

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



来源:https://stackoverflow.com/questions/29697009/correlation-matrix-plot-with-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!