首页 > 解决方案 > 使用ggplot在分类X轴上连接来自不同组的点

问题描述

我正在尝试可视化三种方法之间 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)     

第一个图仅在每个方法中垂直连接点。

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

尝试按factor_1factor_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))

即使我只绘制一行,R 也会抱怨说“geom_path:每个组只包含一个观察值。你需要调整组审美吗?” 并且不连接点。

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

我知道当 X 轴是一个连续变量时可以做到这一点,但是我没有看到它与一个分类变量。

这或多或少是我想要的。它甚至不需要进行彩色编码,因为我可以制作两张图,一张用于“X”,另一张用于“Y”。

预先感谢您的帮助。

标签: rggplot2plotcategorical-data

解决方案


这是你想要的??

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

在此处输入图像描述


推荐阅读