使用 R 中的 ggplot2 在多面、闪避条形图上的每个条形图上的文本居中对齐

Center alignment of text over each bar on faceted, dodged bar plot using ggplot2 in R

我希望我的文本在多面躲避条形图中的每个条形上方居中对齐。

# setup
library(ggplot2); library(tidyverse)
data("iris")

# graph
iris %>% group_by(Species) %>% 
mutate(Petal_Group = ifelse(Petal.Width < median(Petal.Width), "Short", "Long")) %>% 
mutate(Sepal_Group = ifelse(Sepal.Width < median(Sepal.Width), "Short", "Long")) %>% 
group_by(Petal_Group, Sepal_Group, Species) %>% 
summarise(mean.Sepal.Length = mean(Sepal.Length)) %>% 
mutate(asterisks = "***") %>% 
ggplot(aes(x = Petal_Group, y = mean.Sepal.Length)) + 
    geom_col(aes(fill = Species), position = "dodge") + 
    geom_text(aes(label=asterisks, group = Species), position = position_dodge(width = 1)) + 
    facet_grid(~Sepal_Group, labeller = label_parsed) + 
    theme(legend.position = "bottom", panel.background = element_blank(), panel.border = element_rect(colour = "black", fill = NA, size = 0.2), strip.background = element_blank())

在这个例子中(很抱歉,如果它太复杂了,但我正在处理类似的东西),三重星号(“***”)没有在每个条形上居中。即,红色条上的星号出现在左侧,蓝色条上的星号出现在右侧。

我尝试在 geom_text 中调整 hjust,但我无法正确调整。 (难道没有更通用的居中对齐方式,比如 position = "center"?)

geom_bargeom_col 的默认闪避宽度我认为是 0.9,而不是 1,因此您的文字被闪避的量与您的栏不同。如果您创建一个可以应用于列和文本的闪避对象,它们将很好地对齐:

# graph
dodger = position_dodge(width = 0.9)
iris %>% group_by(Species) %>% 
    mutate(Petal_Group = ifelse(Petal.Width < median(Petal.Width), "Short", "Long")) %>% 
    mutate(Sepal_Group = ifelse(Sepal.Width < median(Sepal.Width), "Short", "Long")) %>% 
    group_by(Petal_Group, Sepal_Group, Species) %>% 
    summarise(mean.Sepal.Length = mean(Sepal.Length)) %>% 
    mutate(asterisks = "***") %>% 
    ggplot(aes(x = Petal_Group, y = mean.Sepal.Length)) + 
    geom_col(aes(fill = Species), position = dodger) + 
    geom_text(aes(label=asterisks, group = Species), position = dodger) + 
    facet_grid(~Sepal_Group, labeller = label_parsed) + 
    theme(legend.position = "bottom", panel.background = element_blank(), 
          panel.border = element_rect(colour = "black", fill = NA, 
          size = 0.2), strip.background = element_blank())

结果: