在 r 中的以下 ggplot 中,我希望我的“n”标签与每个条形的左侧对齐 - 因为它们位于粉红色条形上,但不在蓝色条形上。不知何故,躲避并没有转移到右侧蓝色条的 n 标签。
我查看了Position geom_text on dodged barplot,建议使用 dodge(0.9)。这对我的情况没有帮助。这个答案:在多面躲闪条形图顶部添加文本导致我在 ggplot 代码中添加“group =”。这没有帮助。
所有帮助将不胜感激,如果我可以在此处添加任何说明,请告诉我!
这是一个最小的可重现示例:
factor <- c("Included", "Included", "Excluded", "Excluded")
affected <- c("Affected", "Not Affected", "Affected", "Not Affected")
mean_rating <- c(76.00000, 39.55556, 49.00000, 41.62069)
n <- c(23, 2, 17, 19)
df1 <- data.frame(factor, affected, mean_rating, n)
ggplot(df1, aes(x = factor, y = mean_rating, fill = affected, group = affected)) +
geom_bar(stat = "identity", position = position_dodge(0.9)) +
geom_text(aes(label = paste("n =", n), y = mean_rating),
hjust = 1, vjust=-0.35, position = position_dodge(0.9)) +
guides(fill = FALSE, color = FALSE)
问题是标签放置在条的中心,并使用
hjust
标签与该位置的左侧或右侧对齐。相反,要将标签与条形左侧对齐,您必须将标签放置在条形左侧,对于您的情况,可以通过将 x 位置移动 -.9 / 2 / 2
(.9 / 2 = 一半)来实现条形宽度,另一个 ... / 2
来说明 fill
类别的数量)。为此我使用 stage()
,即 x = stage(factor, after_stat = x - .9 / 4)
library(ggplot2)
ggplot(df1, aes(x = factor, y = mean_rating, fill = affected)) +
geom_bar(stat = "identity", position = position_dodge(0.9)) +
geom_text(
aes(
x = stage(factor, after_stat = x - .9 / 2 / 2),
label = paste("n =", n), y = mean_rating
),
hjust = 0,
vjust = -0.35,
position = position_dodge(0.9)
) +
guides(fill = "none", color = "none")