使用 ggplot2 将标签在条形图上居中并将标签移动到 R 中错误条的顶部

Centering labels at the bars using ggplot2 and moving labels to the top of the errorbar in R

使用下面的代码,

library(ggplot2)
load(url("http://murraylax.org/datasets/cps2016.RData"))

ggplot(df, aes(industry, usualhrs, fill=as.factor(sex))) +
  stat_summary(geom = "bar", fun = mean, position = "dodge", width=0.7) +
  stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge", width=0.7) + 
  stat_summary(aes(label = round(..y..,0)), fun = mean, geom = "text", size = 3, vjust = -1) +  
  xlab("Industry") + ylab("Usual Hourly Earnings") +  
  scale_x_discrete(labels = function(x) str_wrap(x, width = 12)) +
  theme(legend.position = "bottom") + 
  labs(fill = "Gender")  +
  theme_bw() 

我正在制作这个条形图(带有误差线):

标签根据 x 轴居中,但我希望标签在每个栏中居中。例如,在前两个柱中,我希望在 "Female" 柱的中心有 27 个,在 "Male" 柱的中心有 46 个。我还想将标签移动到错误栏的顶部。

position = position_dodge(width = 1)) 添加到您的 stat_summary(aes(label...)) 调用中,在 aes 之外将标签移动到各自的栏上方。

为了将标签移动到误差线上方,我使用了 geom_text,y 位置略高于误差线,这需要使用 dplyr::summarize

提前计算误差线位置
library(dplyr)
df %>% 
  group_by(industry, sex) %>% 
  summarise(usualhrs_mean = mean(usualhrs, na.rm = TRUE),
            count = n(),
            usualhrs_se = sd(usualhrs, na.rm = TRUE)/sqrt(count)) %>% 
  ggplot(aes(x = industry, y = usualhrs_mean, fill = as.factor(sex))) +
  geom_bar(stat = "identity", position = position_dodge(width = 1)) +
  geom_errorbar(aes(ymin = usualhrs_mean - usualhrs_se,
                    ymax = usualhrs_mean + usualhrs_se), 
                position = position_dodge(width = 1)) +
  geom_text(aes(label=round(..y.., 0), y = (usualhrs_mean + usualhrs_se + 0.1)), vjust = -1.5, position = position_dodge(width = 1)) +
  scale_x_discrete(
    labels = function(x)
      str_wrap(x, width = 12)
  ) +
  coord_cartesian(ylim = c(0, 55)) +
  theme(legend.position = "bottom") +
  labs(fill = "Gender",
       y = "Usual Hourly Earnings")  +
  theme_bw()