我正在尝试使用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)
但是,这对我来说将标签放在错误的标签上。 如果有人对如何解决此问题或首先造成问题有任何想法,将不胜感激!
答案 0 :(得分:0)
您需要将label = deaths
放在aes()
内,以便ggplot
知道它需要使用deaths
数据框内的ideaths
列而不是独立的{{ 1}}向量
deaths
由reprex package(v0.2.1.9000)于2018-11-19创建