ggplot2堆积条形图数据标签是向后的

时间:2017-11-09 19:52:36

标签: r ggplot2

我想在ggplot2中创建一个堆积条形图,数据标签位于与它们相关的填充区域的中心。我尝试过的代码的标签顺序与它们应该处于相反的顺序。这里是代码示例:

data_rep <- data.frame(Task.Number = c('5.004','5.004','5.01','5.01','5.04','5.04'),
               Within_SLA = rep(c('No','Yes'),3),
               Perc_SLA = c(4.8,95.2,1,99,9.6,90.4))

ggplot(data_rep, aes(x=Task.Number,y=Perc_SLA)) +
geom_bar(aes(fill=Within_SLA),stat="identity",position="stack") +
geom_text(aes(label=Perc_SLA), size = 3) + 
scale_fill_discrete(name = "Within SLA") + 
coord_flip()

这就是我得到的:

enter image description here

1 个答案:

答案 0 :(得分:1)

您还需要为文本标签设置堆叠位置。

ggplot(data_rep, aes(x=Task.Number,y=Perc_SLA, fill=Within_SLA)) +
  geom_bar(stat="identity", position="stack") +
  geom_text(aes(label=Perc_SLA), position =position_stack(vjust = 0.5)) + 
  scale_fill_discrete(name = "Within SLA") +
  coord_flip()

enter image description here