相关性分析
尔云间 一个专门做科研的团队

相关分析是指对两个或多个具备相关性的变量元素进行分析,从而衡量两个因素的的相关密切程度,相关性的元素之间需要存在一定的联系或者概率才可以进行相关性分析。判断数据是否具有相关关系,最直观的方法就是绘制散点图

要判断多个数据的之间的关系,散点图的绘制就会显得比较繁琐,这时候要选择绘制散点矩阵

相关系数
相关系数衡量了两个变量的统一程度,范围是-1~1,‘1’代表完全正相关,‘-1’代表完全负相关。比较常用的是Pearson‘皮尔逊’相关系数、Spearman‘斯皮尔曼’相关系数。在R中,相关性分析的R包:
install.packages("corrplot")
网址:Visualize correlation matrix using correlogram - Easy Guides - Wiki - STHDA
下面小果将带大家用具体的例子来了解相关性的概念:测试数据是ggplot2 包中自带的diamond 数据,每一行为一种钻石,每一列为钻石不同的属性,如carat (克拉), cut (切工), color (色泽), clarity (透明度) 等。数据读进来后,怎么绘制呢?不要着急,小果将一步步带你学习。

首先绘制散点图,横轴是克拉数,纵轴是价格(正相关)qplot(carat,price,data=dat)

绘制散点图,对x,y 值取log,可以看出钻石的克拉数和价格是呈现正相关的。
qplot(log(carat),log(price),data=dat)

颜色、大小、性状和其他属性的设置
qplot(carat,price,data=dat,colour=color)

# 后期应用ggplot() 函数后,可以更加自由的绘制各种组合图形
qplot(carat,price,data=dat,geom=c("point","smooth"))# 添加了一条拟合曲线

大家对相关性是不是有了一些初步的了解了呢?不要着急,下面小果将会带大家学习corrgram绘制相关性:
df <- read.csv("corrplot.csv", row.names = 1)
head(df)
par(bg = "#fdfdfd")
# 左下角
panel.raters <- function (x, y, corr = NULL, ...) {
if (!is.null(corr))
return()
plot.xy(xy.coords(x, y), type = "p",
pch = 20, #点形状
cex = .5, #点大小
...)
abline(lm(y ~ x), lwd = 2) #画拟合线
box(col = "black", lwd = 2) #黑色粗边框
}
# 对角线
textPanel <- function (x = 0.5, y = 0.5, txt, cex, font) {
text(x, y, txt, cex = cex, font = font)
box(col = "black", lwd = 2)
}
# 右上角
panel.fill.cor <- function (x, y, corr = NULL, ...)
{
# 计算相关系数
corr <- round(cor(x, y, use = "pairwise", method = "pearson"),2) # 可以换成"kendall"或 "spearman"
# 自定义背景颜色
ncol <- 14
col.regions <- colorRampPalette(c('darkslateblue', 'navy', 'white', 'firebrick3', 'red'))
pal <- col.regions(ncol)
col.ind <- as.numeric(cut(corr, breaks = seq(from = -1, to = 1, length.out = ncol + 1), include.lowest = TRUE))
# 画背景
par(new=TRUE)
plot(0, type='n', xlim=c(-1,1), ylim=c(-1,1), axes=FALSE, asp=1)
usr <- par("usr")
rect(usr[1], usr[3], usr[2], usr[4], col = pal[col.ind],
border = NA)
# 写相关系数
text(0, 0, labels = corr, cex = 2.5, col = ifelse(corr > 0, "black", "white"))
box(col = "black") #黑色窄边框
}
# 画图并保存到pdf文件
pdf("corrgram.pdf",8,8)
pairs(df[1:5],
gap = .5, #小图之间的空隙
text.panel = textPanel, #对角线
lower.panel = panel.raters, #左下角
upper.panel = panel.fill.cor) #右上角
dev.off()
好了,今天的分享就到这里了,欢迎关注"生信果”,生信入门、R语言、生信图解读与绘制、软件操作、代码复现、生信硬核知识技能、服务器、生物信息学的教程,以及基于R的分析和可视化等原创内容,一起见证小白和大佬的成长。

推荐阅读
