矩阵可视化——R&Stata

矩阵可视化——R&Stata

刚刚逛Github时发现的这个包,地址为:kassambara/ggcorrplot。之前似乎也学习过这个包,但是没有做好笔记。所以这次再学习一下。

ggcorrplot包

安装

1
2
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggcorrplot")

计算相关系数矩阵

1
2
3
4
5
library(ggcorrplot)
data("mtcars")
corr <- round(cor(mtcars), 1)
# 计算相关系数的p值矩阵
corr_pmat <- cor_pmat(mtcars)

相关系数矩阵的可视化

1
ggcorrplot(corr, title = "相关系数矩阵", legend.title = "相关系数")

method参数:色块的形状

1
ggcorrplot(corr, title = "相关系数矩阵", legend.title = "相关系数", method = "circle")

type参数

1
ggcorrplot(corr, type = "lower", outline.col = "white")

1
ggcorrplot(corr, type = "upper", outline.col = "white")

1
ggcorrplot(corr, type = "full", outline.col = "white")

颜色与主题

1
ggcorrplot(corr, hc.order = T, type = "lower", outline.color = "white", ggtheme = ggplot2::theme_linedraw, colors = c("#6D9EC1", "white", "#E46726"))

1
2
library(ggthemes)
ggcorrplot(corr, hc.order = T, type = "lower", outline.color = "white", ggtheme = ggthemes::theme_stata, colors = c("#6D9EC1", "white", "#E46726"))

添加相关系数

1
ggcorrplot(corr, hc.order = TRUE, type = "lower", lab = TRUE)

添加显著性水平

在不显著的色块上打叉

1
ggcorrplot(corr, hc.order = TRUE, type = "lower", p.mat = corr_pmat)

把不显著的色块变成空白

1
ggcorrplot(corr, hc.order = TRUE, type = "lower", p.mat = corr_pmat, insig = "blank")

plotmatrx命令

然后再复习一下Stata的plotmatrix命令。

方差——协方差矩阵可视化

1
2
3
4
5
sysuse auto,clear
reg price mpg trunk weight length turn, nocons
mat regmat = e(V)
plotmatrix, m(regmat) c(green) ylabel(,angle(0)) leg(pos(6))
gre plotmatrix

设置颜色:allcolors

1
2
plotmatrix, m(regmat) allcolors(green*1 green*0.8 green*0.6 green*0.4 red*0.4 red*0.6 red*0.8 red*1.0 ) ylabel(,angle(0)) leg(pos(3) c(1) stack)
gre plotmatrix1

aspec()设定纵轴与横轴的比例

1
2
plotmatrix, m(regmat) allcolors(green*1 green*0.8 green*0.6 green*0.4 red*0.4 red*0.6 red*0.8 red*1.0 ) ylabel(,angle(0)) aspect(1) legend(size(*.4) symx(*.4)) leg(pos(3) c(1) stack)
gre plotmatrix2

相关系数矩阵可视化

1
2
3
4
5
matrix accum R = price mpg trunk weight length turn , nocons dev
matrix R = corr(R)

plotmatrix, m(R) s(-1(0.25)1) c(green) leg(pos(3) c(1) stack)
gre plotmatrix3

By specifying the freq option the correlations are additional printed within each coloured box. Negating the need for a legend.

1
2
plotmatrix, m(R) s(-1(0.25)1) c(dkorange) freq legend(off)
gre plotmatrix4

1
2
plotmatrix, m(R) s(-1(0.25)1) c(navy) freq aspect(1) legend(size(*.4) symx(*.4)) legend(off)
gre plotmatrix5

With additional formatting on the cells

1
2
plotmatrix, m(R) s(-1(0.25)1) c(red) freq formatcells(%5.2f) aspect(1) legend(size(*.4) symx(*.4)) legend(off)
gre plotmatrix6

# R, Stata

评论

程振兴

程振兴 @czxa.top
截止今天,我已经在本博客上写了658.8k个字了!

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×