可以使用 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())
如果您需要自由秤,您可以包裹起来:
ggplot(df_long, aes(x, y)) +
geom_point() +
facet_wrap(~ interaction(y_axis, x_axis), scales = "free")
关于r - 使用 ggplot2 将一组列与另一组列进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48219495/