首页 > 解决方案 > ggpairs:仅绘制相关矩阵的前两行

问题描述

我想用绘图做一些相关性分析。由于我的实际数据太大,我使用mtcars数据框来设置示例。

这里的代码

library(ggplot2)
library(ggcorrplot)

mtcars
library(ggcorrplot)
# Computing correlation matrix
corrmatr_mtcars <- round(cor(subset(mtcars[c(3:7,1)])),1)
head(corrmatr_mtcars[,1:6])
corrmatr_mtcars

# Computing correlation matrix with p-values
corrmatr_mtcars.mat <- cor_pmat(mtcars[c(3:7,1)])
head(corrmatr_mtcars.mat[, 1:6])
corrmatr_mtcars.mat


library(GGally)

ggpairs(mtcars[c(3:7,1)],
        title = "Corr Analysis of...",
        lower = list(continuous = wrap("cor",
                                       size = 3)),
        upper = list(
          continuous = wrap("smooth",
                            alpha = 0.3,
                            size = 0.1))
)

有了这个绘图结果:

在此处输入图像描述

但是,我只对前两个变量与所有其他变量的相关性感兴趣。所以,为了避免不必要的信息和节省地方,我宁愿

  1. 我的情节只显示前两个相关行。所有其他相关性都可以删除。最后,我想像下面这样只需要 3 行。
  2. 随后,Corr-Value 标签应放置在散点图面板上。>br>

在此处输入图像描述

我找不到任何选择这样做。

ggpairs(没有复杂的功能)这甚至通常是可能的吗?
如果是:如何?
如果不是:什么是具有可比结果的方法?

标签: rggplot2matrixcorrelation

解决方案


可以这样做

library(ggplot2)
library(ggcorrplot)

mtcars
library(ggcorrplot)
# Computing correlation matrix
corrmatr_mtcars <- round(cor(subset(mtcars[c(3:7,1)])),1)
head(corrmatr_mtcars[,1:6])
corrmatr_mtcars

# Computing correlation matrix with p-values
corrmatr_mtcars.mat <- cor_pmat(mtcars[c(3:7,1)])
head(corrmatr_mtcars.mat[, 1:6])
corrmatr_mtcars.mat


library(GGally)

gg1 = ggpairs(mtcars[c(3:7,1)],
        title = "Corr Analysis of...",
        lower = list(continuous = wrap("cor",
                                       size = 3)),
        upper = list(
          continuous = wrap("smooth",
                            alpha = 0.3,
                            size = 0.1))
)

gg1$plots = gg1$plots[1:12]
gg1$yAxisLabels = gg1$yAxisLabels[1:2]
gg1

在此处输入图像描述


推荐阅读