带有躲避条形图的geom_text

时间:2015-10-12 11:03:17

标签: r ggplot2 bar-chart

我尝试添加Position geom_text on dodged barplot中的文字 但它不适合我的简单数据

data=data.frame(s=c(10,13,17,8),
                pr=c("a","b","a","b"),
                m=c(rep(as.Date('01.01.2015','%d.%m.%Y'),2), rep(as.Date('01.02.2015','%d.%m.%Y'),2)))

和ggplot

ggplot(data = data 
       ,aes(x = m, y = s,fill=pr ,ymax = max(s)*1.1))+
  geom_bar(position = "dodge",stat="identity")+
  geom_text(aes(y=s/2,label=paste(round(s,3),"%")),position = position_dodge(width=1))+
  scale_x_date(labels = date_format("%m/%y"),breaks = date_breaks("months"))

我得到了

enter image description here

如何在正确的位置添加文本(在每个栏的中间)? 谢谢!

1 个答案:

答案 0 :(得分:7)

你可以尝试

ggplot(data = data, aes(x = as.factor(m), y = s,fill=pr ,ymax = max(s)*1.1)) + 
  geom_bar(position = "dodge", stat="identity") + 
  geom_text(aes(y=s/2,label=paste(round(s,3),"%")),position = position_dodge(.9)) + 
  scale_x_discrete(labels = function(x) format(as.Date(x), "%m/%y")) + 
  xlab("m")