Plot of a correlation matrix in R like in Excel example

后端 未结 3 1189
执笔经年
执笔经年 2021-02-03 15:21

I have been trying to minimize my use of Excel in favor of R, but am still stuck when it comes to display simple data cells as is often needed as the last step of an analysis. T

3条回答
  •  梦谈多话
    2021-02-03 15:38

    Here is an approach using base graphics:

    par( mar=c(1,5,5,1) )
    plot.new()
    plot.window( xlim=c(0,10), ylim=c(0,11) )
    
    quant_vals <- findInterval( cor_matrix[-11,], 
        c(-Inf, quantile(cor_matrix[-11,], c(0.05, 0.25, 0.45, 0.55, 0.75, 0.95), na.rm=TRUE ),
                Inf) )
    quant_vals[ is.na(quant_vals) ] <- 4
    cols <- c('#ff0000','#ff6666','#ffaaaa','#ffffff','#aaffaa','#66ff66','#00ff00')
    colmat <- matrix( cols[quant_vals], ncol=10, nrow=10)
    
    rasterImage(colmat, 0, 1, 10, 11, interpolate=FALSE)
    for(i in seq_along( cor_matrix[11,] ) ) {
        rect( i-1, 0.1, i-1 + cor_matrix[11,i]/max(cor_matrix[11,]), 0.9, col='lightsteelblue3')
    }
    
    text( col( cor_matrix )-0.5, 11.5-row( cor_matrix ), cor_matrix, font=2 )
    rect( 0,1,10,11 )
    rect( 0,0,10,1)
    axis(2, at=(11:1)-0.5, labels=rownames(cor_matrix), tick=FALSE, las=2)
    axis(3, at=(1:10)-0.5, labels=colnames(cor_matrix), tick=FALSE, las=2)
    
    rect(0,8,3,11, lwd=2)
    rect(4,4,7,7, lwd=2)
    rect(8,1,10,3, lwd=2)
    

提交回复
热议问题