ggplot2 中的图对型矩阵

问题描述 投票:0回答:1

我正在处理一个具有单个回归器和

d
许多响应变量的数据集。在处理这个问题时,我遇到了一个相关性数据框,其中
1 + dC2 = 1 + d(d-1)/2
与可以在 here 找到的数据框完全一样。我正在插入此类数据框的示例:

   X      r_{1,2}     r_{1,3}      r_{1,4}      r_{1,5}      r_{2,3}      r_{2,4}      r_{.,.}
1 21    0.6002993    0.923644    0.8184414    0.3721132    0.9337539    0.6569090    .........
2 22    0.6498641    0.358339    0.9511748    0.1091543    0.6651190    0.9960394    .........
3 23    0.6825716    0.117533    0.8900186    0.9256916    0.9253819    0.6588873    .........
4 24    0.8280786    0.324110    0.6634117    0.7292685    0.0207334    0.9122315    .........
5 25    0.9520840    0.642721    0.5012283    0.2722650    0.2582217    0.3901019    .........
6 26    0.8714017    0.157062    0.8675581    0.5384571    0.6053657    0.5930488    .........
.  .        .
.  .        .
.  .        .

数据帧的第一列是时间变量

X
,任何其他标题为
r_{i,j}
的列都包含第
i
j
变量之间随时间变化的相关性。

现在,我正在尝试使用

ggplot2
或类似的包为每对变量制作一个时变相关性图矩阵。手动完成这可能不是很困难,但由于我有很多变量,因此该过程必须自动化。本质上,我想要的情节如下所示:


请注意:

对于每个图,X 轴是相同的,即数据框中的变量
    d
  • ,轴文本位于最底部。
    每个图中的 Y 尺度应相同,即 0 到 1。
  • 最后,行和列中都应该有行和列名称,如 1,2,3,...。
任何帮助将不胜感激。如果需要任何说明,请告诉我。谢谢!

r ggplot2 plot correlation ggpairs
1个回答
0
投票

X


使用的数据

library(ggplot2) library(patchwork) # Find dimension of square matrix n <- which(choose(seq(20), 2) == ncol(df) - 1) # XY plot of each column versus x plots <- lapply(2:ncol(df), function(i) { ggplot(df, aes(x, .data[[names(df)[i]]])) + geom_line() + labs(y = NULL) + theme_classic() + theme(axis.text.x = if(grepl(paste0(",", n), names(df)[i])) { element_text() } else { element_blank() }, axis.title.x = if(grepl(paste0(",", n), names(df)[i])) { element_text() } else { element_blank() }) }) # Create design matrix for plot m <- matrix(rep("#", n^2), nrow = n) m[lower.tri(m)] <- LETTERS[seq(ncol(df) - 1)] d <- paste(apply(m[2:n, 1:(n-1)], 1, paste, collapse = ""), collapse = "\n") # Draw plots Reduce(`+`, plots) + plot_layout(design = d)

创建于 2023-07-30,使用 

reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.