簡體   English   中英

使用ggplot在分類X軸上連接來自不同組的點

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

我試圖在三種方法之間可視化 A、B 和 C 的豐度變化。 A、B 和 C 也分為兩組(“X”和“Y”)。 我正在嘗試用 ggplot 將這些 plot 與方法連接起來,但我無法做到。 這就是我所做的:

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)     

第一個 plot 僅在每個方法中垂直連接點。

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))

即使我 plot 只有一排,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”。

預先感謝您的幫助。

這是你想要的??

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM