geom_text 错误地标记条形图

geom_text labelling bars incorrectly

我正在尝试使用 ggplot 在 R 中创建图表。在我尝试使用 geom_text 添加标签之前,该图很好。

数据:

year <-c(2016,2017,2016,2017,2016,2017,2016,2017,2016,2017,2016,2017,2016,2017)
age <- c("0-15","0-15","16-25","16-25","26-35","26-35","36-45","36-45","46-55","46-55","56-65","56-65","66+","66+")
deaths <- c(10,4,40,33,38,28,23,22,18,22,13,16,44,33)
age_group <- factor(age)
fyear <- factor(year)

ideaths <- data.frame(fyear,age_group,deaths)

这是我目前的代码

ggplot(data = ideaths,mapping = aes(x = age_group, y=deaths, 
fill=fyear)) +
geom_bar(position = "dodge", stat="identity", width=0.5) + 
geom_text(label=deaths,vjust=-0.5) + ggtitle("Figure 8.") +
scale_fill_manual(values=c("#7F7F7F","#94D451")) +
scale_y_continuous(breaks=seq(0,55,5)) + theme_light() +
theme(panel.border = element_blank(), panel.grid.major.x = 
element_blank(), panel.grid.minor.y = 
element_blank(),panel.grid.major.y = element_line( size=.1, 
color="grey"), axis.title = element_blank(), legend.position 
= "bottom", legend.title=element_blank(), plot.title 
=element_text(size=10))  

这给了我这张图:

我搜索了如何将标签与条对齐并找到 position=position_dodge(width=0.9)

但是,这对我来说是错误的标签。 如果有人知道如何解决这个问题,或者首先是什么原因导致的,我们将不胜感激!

你需要把 label = deaths 放在 aes() 里面,所以 ggplot 知道它需要使用 ideaths 数据框里面的 deaths 列而不是独立的deaths向量

library(ggplot2)

ggplot(data = ideaths, aes(x = age_group, y = deaths, fill = fyear)) +
  geom_col(position = position_dodge(width = 0.9)) +
  geom_text(aes(x = age_group, y = deaths + 3, label = deaths), 
            position = position_dodge(width = 0.9)) +
  ggtitle("Figure 8.") +
  scale_fill_manual(values = c("#7F7F7F", "#94D451")) +
  scale_y_continuous(breaks = seq(0, 55, 5)) + 
  theme_light() +
  theme(
    panel.border = element_blank(), 
    panel.grid.major.x = element_blank(), 
    panel.grid.minor.y = element_blank(), 
    panel.grid.major.y = element_line(size = .1, color = "grey"), 
    axis.title = element_blank(), legend.position = "bottom", 
    legend.title = element_blank(), plot.title = element_text(size = 10)
  )

reprex package (v0.2.1.9000)

创建于 2018-11-19