r - 使用 ggplot2 将标签置于条形中心并将标签移动到 R 中误差条的顶部

标签 r ggplot2 label bar-chart errorbar

使用下面的代码,

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。我还想将标签移动到错误栏的顶部。

最佳答案

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

关于r - 使用 ggplot2 将标签置于条形中心并将标签移动到 R 中误差条的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61955157/

相关文章:

r - 在散点图中绘制 95% 置信限

r - 如何在QPLOT中使 `geom_text`识别 `aes`(R编程)

r - 如何强制 saveWidget 在 RStudio 之外创建单个文件?

根据 data.table 中的子字符串对选定列进行行操作

r - 在两个公共(public)列 R 的匹配值上连接两个数据帧

iphone - 设置标签字体

r - 如何使用 ggplot2 R 增加整个图的宽度

python - 使用 pandas,我如何有效地按组对大型 DataFrame 进行子采样?

r - 如何使用R创建时间螺旋图

javascript - 使用 javascript 获取关联的单选按钮标签文本