R语言 在分组箱线图中连接每个受试者的闪避点

fnatzsnv  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(298)

我有一些分组的数据,我想位置躲避箱线图和位置躲避点,我想添加一条线连接一个组内的点。

library(tidyverse)
mock_data <- tibble::tribble(
  ~Subject, ~Marker, ~Cell_type, ~Value,
        "1",     "A",        "B",    70L,
        "2",     "A",        "B",    80L,
        "3",     "A",        "B",    90L,
        "1",     "A",        "T",     5L,
        "2",     "A",        "T",    10L,
        "3",     "A",        "T",    15L,
        "1",     "B",        "B",     1L,
        "2",     "B",        "B",     2L,
        "3",     "B",        "B",     3L,
        "1",     "B",        "T",    99L,
        "2",     "B",        "T",    90L,
        "3",     "B",        "T",    99L
  )

我想看到的是:

我在geom_line中尝试了各种分组,但似乎无法获得预期的输出

mock_data |> 
  ggplot(aes(x = Marker, y = Value)) +
  geom_boxplot(aes(fill = Cell_type), alpha = 0.2) +
  geom_point(aes(col = Subject, group = Cell_type), position = position_dodge(width = 0.75), size = 3) +
  geom_line(aes(group = Subject), lty = 2, col = "black")

给我:

有什么想法吗?谢谢

4si2a6ki

4si2a6ki1#

我们可以按Maker分面,并将Cell_type放在“x”轴上

mock_data |> 
  ggplot(aes(x = Cell_type, y = Value)) +
  geom_boxplot(aes(fill = Cell_type), alpha = 0.2) +
  geom_point(aes(col = Subject, group = Cell_type), position = position_dodge(width = 0.75), size = 3) +
  geom_line(aes(group = Subject), lty = 2, col = "black") +
  facet_wrap(~Marker, strip.position = "bottom") +
  theme(
    axis.title.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    strip.background = element_blank()
    )

创建于2023-04-26带有reprex v2.0.2

ulmd4ohb

ulmd4ohb2#

对于一般的兴趣,这里有一个替代的解决方案,不需要刻面。然而,它确实需要“人工”生成线段的x坐标。

segment_positions <- mock_data |> 
  pivot_wider(id_cols = c(Subject,Marker), names_from = Cell_type, values_from = Value) |>
  mutate(x1 = as.numeric(Marker == 'B') + 1 - .75/4, x2 = as.numeric(Marker == 'B') + 1 + .75/4)

mock_data |> 
  ggplot(aes(x = Marker, y = Value)) +
  geom_boxplot(aes(fill = Cell_type), alpha = 0.2) +
  geom_point(aes(col = Subject, group = Cell_type), position = position_dodge(width = 0.75), size = 3) +
  geom_segment(data = segment_positions, aes(x = x1, xend = x2, y = B, yend = T), lty = 2, col = "black")

请注意,x坐标的偏移量是0.75/4,因为总减淡宽度是0.75。这意味着每个箱形图在减淡的每一侧都偏移了总宽度的一半(0.75/2)。因为这些点位于箱形图的中间,所以它们偏移了每个箱形图偏移宽度的一半(0.75/4)。

相关问题