如何在 R 中的躲避条上方绘制连接成对点的线?

How to draw lines connecting pair-wise points above dodging bars in R?

我认为这个问题非常复杂,代码示例会有所帮助:

library(ggplot2)

df <- data.frame(
  Group = c("A", "A", "A", "A", "B", "B"),
  Subgroup = c("A.1", "A.2", "A.1", "A.2", "B.1", "B.2"),
  Value = c(10, 7, 8, 9, 11, 12),
  Pair = c(1, 1, 2, 2, 3, 3)
)

dodge <- position_dodge(width = 0.9)
ggplot(data = df, mapping = aes(x = Group, y = Value, fill = Subgroup)) +
  geom_bar(stat = "summary", fun = "mean", position = dodge) +
  geom_point(position = dodge) +
  geom_line(color = "red", mapping = aes(group = Pair), position = dodge)

关键是要有一个包含组和子组的条形图(成功),在每个条形图上方居中绘制各个点(成功),以及连接成对样本的线(失败)。结果相差不远,但显然,ggplot2 绘制垂直线,然后让 它们 避开每个点,而不是让点彼此避开然后画线其他.

实际:

预计:

可能更容易被 Group 分面,完全放弃位置调整。下面还包含标签、面板间距等,以尽可能模仿原始绘图的外观。

library(ggplot2)

ggplot(df, aes(x = Subgroup, y = Value, fill = Subgroup)) +
  geom_bar(stat = "summary", fun = "mean", width = 1) +
  geom_point() +
  geom_line(aes(group = Pair), color = "red", ) +
  facet_wrap(vars(Group), scales = "free_x", strip.position = "bottom") +
  labs(x = "Group") +
  theme(
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    strip.background = element_blank(),
    panel.spacing = unit(0, units = "line")
  )