【问题标题】:facet or grouped correlation and correlogram plots in RR中的刻面或分组相关和相关图
【发布时间】:2017-07-21 01:02:42
【问题描述】:

我正在尝试从数据框中按组/方面绘制相关图。如果我对每个变量的数据进行子集化,我就可以做到这一点。如何一次对所有变量执行此操作以根据每个变量生成分面图?

###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?

【问题讨论】:

    标签: r ggplot2 grouping correlation facet


    【解决方案1】:

    @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)}
    

    【讨论】:

      【解决方案2】:

      据我了解,您希望每个 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)
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-22
        • 1970-01-01
        • 2015-06-14
        • 2022-01-03
        • 1970-01-01
        • 2015-02-10
        • 1970-01-01
        相关资源
        最近更新 更多