r - 使用 ggplot2 将一组列与另一组列进行比较

标签 r ggplot2 tidyr tidyverse

可以使用 ggplot2 来创建一组列与另一组列的绘图矩阵吗?

例如,使用下面的数据框绘制以“x”开头的所有列与以“y”开头的所有列,以生成绘图网格。

require("tidyverse")

df <- tibble(
  x1 = sample(10),
  x2 = sample(10),
  x3 = sample(10),
  y1 = sample(10),
  y2 = sample(10)
)

如果与上面的示例不同,列没有以常规模式命名,该怎么办 - 有没有办法可以选择任意列集?

提前致谢

最佳答案

您可以使用 tidyr::gather reshape 形状,然后使用facet:

df_long <- df %>% 
  gather(x_axis, x, contains("x")) %>% 
  gather(y_axis, y, contains("y"))
# A tibble: 60 x 4
   x_axis     x y_axis     y
    <chr> <int>  <chr> <int>
 1     x1    10     y1     6
 2     x1     6     y1    10
 3     x1     5     y1     3
 4     x1     7     y1     8
 5     x1     8     y1     2
 6     x1     1     y1     1
 7     x1     3     y1     5
 8     x1     9     y1     9
 9     x1     4     y1     7
10     x1     2     y1     4
# ... with 50 more rows

您可以使用任何其他 tidyverse 选择函数来代替 contains,或者只提供原始列名称。

然后绘制:

ggplot(df_long, aes(x, y)) + 
    geom_point() + 
    facet_grid(y_axis ~ x_axis, switch = "both") +
    labs(x = NULL, y = NULL) +
    theme(strip.placement = "outside", strip.background = element_blank())

enter image description here

如果您需要自由秤,您可以包裹起来:

ggplot(df_long, aes(x, y)) + 
    geom_point() + 
    facet_wrap(~ interaction(y_axis, x_axis), scales = "free")

enter image description here

关于r - 使用 ggplot2 将一组列与另一组列进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48219495/

相关文章:

r - 与管道运算符和 [ 选择器一起使用时,为什么 colnames 函数会生成小标题(而不是矢量)?

r - 在ggplot函数或geom中设置aes之间的区别?

R:检测 "main"路径并使用内核删除或过滤GPS轨迹?

r - 将 tidyr complete() 与变量中指定的列名一起使用

r - 使用不同长度的向量与 tidyr 分开

r - 如何重新采样捕捉到现有网格的栅格?

r - 使用 R 中的 reshape2 函数融化和附加数据

r - 如何随机化列顺序的子集

r - x 轴的斜体标签

r - 在 ggplot2 箱线图中添加每组和子组的多个观察值