這篇文章是一個英文教程的搬運和整理,前幾天在論文中看到了非常漂亮的相關圖(correlogram),可以通過這個畫出來。相關圖可以非常好的表現數據表中的各個變量之間的相關關係。在相關圖中,相關係數(correlation coefficients) 根據不同的值賦予了不同的顏色,相關矩陣(correlation matrix) 可以根據不同變量間的關係表現出來。在這裡使用了R語言中的corrplot包。
安裝corrplot包要想在R語言中繪製相關圖,需要先安裝R包。在這裡使用的是「corrplot」包,具體的R語言安裝介紹請看前面的推文R語言安裝部署基礎。
R語言安裝部署基礎準備數據實驗數據使用的是R語言中經典的mtcars
head(mtcars)計算相關矩陣
M<-cor(mtcars) #計算相關
head(round(M,2)) #保留兩位小數相關矩陣計算結果相關圖:可視化相關矩陣
使用R語言corrplot函數即可實現相關圖的繪製。語法如下:
corrplot(corr, method="circle")
參數介紹corr用來繪圖的相關矩陣method可視化方式,可以為圓、顏色、數字等等不同的可視化方法總共七種:方法分別為:「circle」, 「square」, 「ellipse」, 「number」, 「shade」, 「color」, 「pie」.
library(corrplot)
corrplot(M, method="circle")corrplot(M, method="pie")corrplot(M, method="color")corrplot(M, method="number")相關圖的排版
相關圖有三種排版方式:
corrplot(M, type="upper")corrplot(M, method = "color",type="lower")重新排列相關矩陣
相關矩陣可以根據相關係數進行重新排列,這對於發現矩陣中的結構特點是非常重要的。「hclust」可以使用層次聚類法進行排布。
corrplot(M, method = "color",type="upper", order="hclust")# 使用不同的色彩
col<- colorRampPalette(c("red", "white", "blue"))(20)
corrplot(M, type="upper", order="hclust", col=col)# 將背景改為淺藍色
corrplot(M, type="upper", order="hclust", bg="lightblue")分級設色
相關圖的顏色可以自定義。使用RcolorBrewer包可以進行調色,並分級設色。
library(RColorBrewer)
corrplot(M, type="upper", order="hclust",
col=brewer.pal(n=8, name="RdBu"))分級設色8級
這個顏色的詳細信息可以從配色網站查詢:
https://tidyfriday.cn/colors/#type=sequential&scheme=BuGn&n=3https://colorbrewer2.org/第一個是國內的,不過網站不太穩定,打開比較慢;第二個是國外的,需要翻牆,否則顯示不全。
改變標註的顏色和方向使用tl.col參數控制坐標軸標註顏色,使用tl.srt控制坐標軸標註旋轉方向
corrplot(M, type="upper", order="hclust", tl.col="black", tl.srt=45)坐標軸標註黑色,旋轉45°給相關圖添加顯著性檢驗計算相關的p值
計算相關的p值矩陣,代碼如下:
# mat : 數據的矩陣
#自定義了cor.mtest函數
# ... : further arguments to pass to the native R cor.test function
cor.mtest <- function(mat, ...) {
mat <- as.matrix(mat)
n <- ncol(mat)
p.mat<- matrix(NA, n, n)
diag(p.mat) <- 0
for (i in 1:(n - 1)) {
for (j in (i + 1):n) {
tmp <- cor.test(mat[, i], mat[, j], ...)
p.mat[i, j] <- p.mat[j, i] <- tmp$p.value
}
}
colnames(p.mat) <- rownames(p.mat) <- colnames(mat)
p.mat
}
# matrix of the p-value of the correlation
p.mat <- cor.mtest(mtcars)
head(p.mat[, 1:5])運行結果給相關圖添加顯著性
# Specialized the insignificant value according to the significant level
corrplot(M, type="upper", order="hclust",
p.mat = p.mat, sig.level = 0.01)顯著性水平0.01
# Leave blank on no significant coefficient
corrplot(M, type="upper", order="hclust",
p.mat = p.mat, sig.level = 0.01, insig = "blank")不滿足顯著性的表示為空白自定義相關圖
col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
corrplot(M, method="color", col=col(200),
type="upper", order="hclust",
addCoef.col = "black", # Add coefficient of correlation
tl.col="black", tl.srt=45, #Text label color and rotation
# 添加顯著性
p.mat = p.mat, sig.level = 0.01, insig = "blank",
# hide correlation coefficient on the principal diagonal
diag=FALSE
)
參考文獻http://www.sthda.com/english/wiki/visualize-correlation-matrix-using-correlogram#introductionhttps://colorbrewer2.org/https://cran.r-project.org/web/packages/corrplot/index.html