簡體   English   中英

R中的分面或分組相關和相關圖

[英]facet or grouped correlation and correlogram plots in R

我正在嘗試從數據框中按組/構面繪制相關圖。 如果我將每個變量的數據子集化,我就能做到這一點。 如何一次對所有變量執行此操作,以基於每個變量生成構面圖?

###Load libraries
library(gdata)
library(corrplot)
library(ggplot2)
library(gtable)
library(ggpmisc)
library(grid)
library(reshape2)
library(plotly)
packageVersion('plotly')

##Subset ample data from the "iris" data set in R
B<-iris[iris$Species == "virginica", ]

##calculate correlation for numeric columns only
M<-cor(B[,1:4])
head(round(M,2))

###calculate significance
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(B[,1:4])

###plot
#color ramp
col<- colorRampPalette(c("red","white","blue"))(40)
corrplot(M, type="upper",tl.col="black", tl.cex=0.7,tl.srt=45, col=col,
p.mat = p.mat, insig = "blank", sig.level = 0.01)

這很好,因為我從數據框中僅取出了一個變量“ virginica”。 如何自動執行此操作以進行唯一的相關性計算,然后對所有單個變量作為各個方面進行Corrplot?

據我了解,您想要每個Species級別的Corrplot。 因此,您可以嘗試:

library(Hmisc) # this package has implemented a cor function calculating both r and p.  
library(corrplot)
# split the data 
B <- split(iris[,1:4], iris$Species)
# Calculate the correlation in all data.frames using lapply 
M <- lapply(B, function(x) rcorr(as.matrix(x)))

# Plot three pictures
par(mfrow=c(1,3))
col<- colorRampPalette(c("red","white","blue"))(40)
lapply(M, function(x){
corrplot(x$r, type="upper",tl.col="black", tl.cex=0.7,tl.srt=45, col=col,
         p.mat = x$P, insig = "blank", sig.level = 0.01)
})

在此處輸入圖片說明

@Jimbou,感謝您的代碼。 我對其進行了一些編輯,以在一個代碼中添加相關性分析,唯一的R和圖,並為每個圖添加唯一的名稱。 標題圖

library(ggplot2)
library(Hmisc) 
library(corrplot)
# split the data 
B <- split(iris[,1:4], iris$Species)
##extract names
nam<-names(B)
# Plot three pictures
par(mfrow=c(1,3))
col<- colorRampPalette(c("red","white","blue"))(40)
for (i in seq_along(B)){
# Calculate the correlation in all data.frames using lapply 
M<-rcorr(as.matrix(B[[i]]))
corrplot(M$r, type="upper",tl.col="black", tl.cex=0.7,tl.srt=45, col=col,
 addCoef.col = "black", p.mat = M$P, insig = "blank",sig.level = 0.01)
mtext(paste(nam[i]),line=1,side=3)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM