前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R语言 相关系数混合可视化矩阵实现

R语言 相关系数混合可视化矩阵实现

作者头像
拴小林
发布2020-07-10 16:00:45
1K0
发布2020-07-10 16:00:45
举报
文章被收录于专栏:数据驱动实践数据驱动实践

相关系数可视化图让我们清晰了解变量之间的相关性,corrplot作为一个相关系数的多样式展示包,对我们的科研学习帮助巨大

01

效果图

02

上代码

相关矩阵可视化包:corrplot

### 声  明:本内容为作者借助R3.6.3和Rstudio及相关包制作而成,仅供学习交流,咨询交流加wx:huyanggs 或Email:huyanggs@hotmail.com
### 主  题:相关性分析图表可视化
### 数据源:R自带数据集mtcars
### author:@拴小林Nobeli
### 时  间:2020/3/28


## 1.读取并了解数据集
data(mtcars)
# > names(mtcars)
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"

df <- mtcars
# > str(df)
# 'data.frame':  32 obs. of  11 variables:
#   $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
# $ disp: num  160 160 108 258 360 ...
# $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
# $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
# $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
# $ qsec: num  16.5 17 18.6 19.4 17 ...
# $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
# $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
# $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
# $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

## 2.相关系数计算
res <- cor(df)

## 3.安装并加载corrplot包
# install.packages("corrplot")
library(corrplot)

1.简单相关性系数可视化

corrplot(res)
# 不同method的相关性系数图表
corrplot(res,method="pie",tl.col="black",tl.srt=45, title = "method=pie的饼图", cex.main = 1, mar = c(2,2,3,2))  #饼图
corrplot(res,method="ellipse",shade.col=NA,tl.col="black",tl.srt=45,  title = "method=ellipse的饼图", cex.main = 1, mar = c(2,2,3,2)) #椭圆
corrplot(res, method="number",shade.col=NA,tl.col="black",tl.srt=45,  title = "method=number的饼图", cex.main = 1, mar = c(2,2,3,2))#数字
# 参数解释
# method:展示方法
# shade.col:背景颜色
# tl.col:坐标颜色;tl.srt:坐标内容旋转角度
# title:设置标题
# cex.main:标题相对于默认大小的调整倍数
# mar:图形元素的边距,默认“下左上右”顺序

# 学习更多# ??corrplot

2.混合相关性系数可视化

(上下三角矩阵)

corrplot(res, type = "upper", order = "hclust", tl.col = "black", tl.srt = 45, 
         title = "type = upper的数字+饼图", mar = c(2,2,3,2))  #上三角


corrplot.mixed(res, title = "图形和数值混合矩阵", mar = c(2,2,3,2)) #图形和数值混合矩阵

corrplot.mixed(res, lower.col = "black", number.cex = .7, 
               title = "文字看不清,可以设置文字为黑色lower.col和大小number.cex", mar = c(2,2,3,2))


corrplot(res, order = "hclust", addrect = 2, 
         title = "按hclust聚类方式排序", mar = c(2,2,3,2))  
#按hclust聚类方式排序,addrect是添加分组矩形,可自定义分组类
#类似于平时热图的kmean分组方式。

03

源代码

源数据及R代码:

链接: https://pan.baidu.com/s/1AnDwMpENSLgTlkzHpac3XQ

提取码: sx46

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据驱动实践 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档