考虑到 position='dodge' 的条形图,如何在柱形条形图上添加线条,其中线条经过条形图的中间顶部?

how to add lines over a column bar graph where the lines pass by the middle-top of the bars considering bars with position='dodge'?

这里我提供一个我尝试过的例子:

df <- data.frame(a = rep(c(1:12), each = 2),
                 b = c("yes", "no"),
                 c = sample(x = 1:200, size = 24))

ggplot(df, aes(x = a, y = c)) + 
  geom_col(aes(fill = b), position = 'dodge') +
  scale_x_continuous(breaks = min(a):max(a)) +
  geom_line(aes(x = a, y = c, group = b), stat = "identity")

所以基本上我想要获得的是每个 xtick 的两个柱,每个柱组的一条线经过每个匹配柱的顶部中心。我希望这两条线的颜色与它们匹配的条形集相对应。

我看到这里贴了一个C语言的问题。它与这个问题有一些相似之处,但帮助不大。

如果有人知道如何实现这一点,我将不胜感激:)

关键是geom_colgeom_line都要设置position = position_dodge()

如果将线条颜色设置为与条形相同的颜色,则很难将线条可视化。这里我通过scale_color_manual手动设置“no”为“black”,“yes”为“firebrick”。删除代码 scale_color_manual(values = c("no" = "black", "yes" = "firebrick"), name = "line") 以使颜色与条形对齐。

library(ggplot2)
df <- data.frame(a = rep(c(1:12), each = 2),
                 b = c("yes", "no"),
                 c = sample(x = 1:200, size = 24))

ggplot(df, aes(x = a, y = c, group = b, fill = b)) + 
  geom_col(position = position_dodge(width = 1)) +
  geom_line(aes(col = b), position = position_dodge(width = 1)) +
  scale_color_manual(values = c("no" = "black", "yes" = "firebrick"), name = "line")

reprex package (v2.0.1)

于 2022-05-05 创建