简体   繁体   English

寻找 plot 成对散点图矩阵的方法,其中变量分为两组

[英]Looking for a way to plot a pairwise scatterplot matrix where variables are in two groups

Looking for a way to plot a pairwise scatterplot matrix where variables are in two groups, ie the plots need to be restricted to pairs between groups, excluding within-group pairs.寻找一种方法来 plot 成对散点图矩阵,其中变量位于两组中,即图需要限制为组之间的对,不包括组内对。 For instance, the base pairs() produces this例如,碱基pairs()产生这个

    pairs(iris[1:4])

在此处输入图像描述

Whereas I am looking to, for example, correlate only sepal variables with petal variables, and am not interested in sepal (or petal) length-to-width correlations.例如,我希望仅将萼片变量与花瓣变量相关联,并且对萼片(或花瓣)长度与宽度的相关性不感兴趣。 So, instead of a 4x4 matrix, I'd need a 2x2 matrix.所以,我需要一个 2x2 矩阵,而不是 4x4 矩阵。

The solution would look something like this解决方案看起来像这样

在此处输入图像描述

pairs() seems to support a formula argument, but pairs(Sepal.Length + Sepal.Width ~ Petal.Length + Petal.Width, data=iris) doesn't look right. pairs()似乎支持公式参数,但是pairs(Sepal.Length + Sepal.Width ~ Petal.Length + Petal.Width, data=iris)看起来不正确。 It's in the right direction giving a 3x3 matrix, but for some reason the two sepal variables are grouped.它给出了一个 3x3 矩阵的正确方向,但由于某种原因,这两个 sepal 变量被分组。

Preferably looking for a solution in ggplot2 or GGally::ggpairs() .最好在ggplot2GGally::ggpairs()中寻找解决方案。

Here is a vanilla ggplot approach with tidyr preprocessing.这是一个带有 tidyr 预处理的香草 ggplot 方法。

First, we'll reshape the data such that the width and length variables have the same columns.首先,我们将重塑数据,使宽度和长度变量具有相同的列。

library(ggplot2)

df <- tidyr::pivot_longer(iris, c(Petal.Length, Petal.Width), 
                          names_to = "petal_metric", values_to = "petal_value")
df <- tidyr::pivot_longer(df, c(Sepal.Length, Sepal.Width),
                          names_to = "sepal_metric", values_to = "sepal_value")

Next, we can simply facet on the petal/sepal metrics.接下来,我们可以简单地分析花瓣/萼片指标。

p <- ggplot(df, aes(sepal_value, petal_value, colour = Species)) +
  geom_point()
  
p + facet_grid(petal_metric ~ sepal_metric)

We could decorate the plot a bit better to have the strips serve as axis titles.我们可以更好地装饰 plot 以将条带用作轴标题。

p + facet_grid(petal_metric ~ sepal_metric, switch = "both") +
  theme(strip.placement = "outside",
        strip.background = element_blank(),
        axis.title = element_blank())

Created on 2022-01-11 by the reprex package (v2.0.1)代表 package (v2.0.1) 于 2022 年 1 月 11 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM