使用ggplot连接分类X轴中不同组的点

Connecting points from different groups in a categorical X axis with ggplot

我正在尝试可视化三种方法之间 A、B 和 C 丰度的变化。 A、B、C也分为两组("X"和"Y")。我正在尝试用 ggplot 绘制这些图,并将方法与方法之间的观察结果联系起来,但我没能做到。这就是我所做的:

factor_1 <- c(rep(c("A", "B", "C"), times =6))
Abundance <- c(sample(x = 1:100, replace = T, size = 18))
factor_2 <- c(rep(c("X", "Y"), each = 3, times = 3))
factor_3 <- c(rep(c("Method 1", "Method 2", "Method 3"), each = 6))
datframe <- tibble(factor_1, factor_2, Abundance, factor_3)     

The first plot only connects the dots vertically in each Method.

datframe %>%
  ggplot(aes(x = factor_3, y = Abundance, color = factor_2))+
  geom_point() +
  geom_line()

当尝试按 factor_1 or factor_2 进行分组时,它似乎将所有内容都连接在一条线上

datframe %>%
  ggplot(aes(x = factor_3, y = Abundance, color = factor_2))+
  geom_point() +
  geom_line(group = c(factor_2))

datframe %>%
  ggplot(aes(x = factor_3, y = Abundance, color = factor_2))+
  geom_point() +
  geom_line(group = c(factor_1))

Even if I plot only one row, R complains, saying "geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?" and does not connect the dots.

datframe %>%
  filter(factor_1 == "A", factor_2 == "X") %>%
  ggplot(aes(x = factor_3, y = Abundance, color = factor_2))+
           geom_point() +
           geom_line()

我知道当X轴是连续变量时可以做到,但是我没看到用分类变量。

This is more or less what I want. It does not need even to be colored coded, since I could make two plots, one for "X" and another for "Y".

预先感谢您的帮助。

这是您要找的东西吗??

datframe %>%
  ggplot(aes(x = factor_1, y = Abundance, color = factor_2, group = factor_2))+
  geom_point() +
  geom_line() +
  facet_wrap(~factor_3)

一种方法是 interaction:

library(ggplot2)
datframe %>%
  ggplot(aes(x = factor_3, y = Abundance, color = factor_2, group = interaction(factor_1,factor_2)))+
  geom_point() + 
  geom_line()

您还可以考虑加入第二种视觉美学来区分 factor_1

datframe %>%
  ggplot(aes(x = factor_3, y = Abundance, color = factor_2, linetype = factor_1, group = interaction(factor_1,factor_2)))+
  geom_point() + 
  geom_line()

数据

set.seed(1)
datframe <- tibble(factor_1 = rep(c("A", "B", "C"), times =6),
                   Abundance = sample(x = 1:100, replace = T, size = 18),
                   factor_2 = rep(c("X", "Y"), each = 3, times = 3),
                   factor_3 = rep(c("Method 1", "Method 2", "Method 3"), each = 6))