使用ggplot2将标签居中,并在R中将标签移动到误差条的顶部[重复]

问题描述 投票:1回答:1

用下面的代码。

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() 

我正在制作这个条形图(带误差条)。

Output

标签根据X轴居中,但我希望每个条形图的标签都居中。例如,在前两个条形图中,我希望 "女性 "条形图的中心是27,"男性 "条形图的中心是46。我还想把标签移到错误条的顶部。

r ggplot2 label bar-chart errorbar
1个回答
2
投票

添加 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() 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.