8

I try to add text as in Position geom_text on dodged barplot But its not work with my simple data

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)))

And 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"))

i get

enter image description here

How to add text in right position( in the middle of each bar)? Thanks!

Community
  • 1
  • 1
Batanichek
  • 7,761
  • 31
  • 49
  • 1
    Try `width=30` instead of `width=1` and it will work – LyzandeR Oct 12 '15 at 11:08
  • 1
    Possible duplicate of http://stackoverflow.com/questions/12018499/how-to-put-labels-over-geom-bar-for-each-bar-in-r-with-ggplot2 ( `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"))` ). – lukeA Oct 12 '15 at 11:20
  • LyzandeR is right, here the widths of columns are not equal to 1, they correspond to the number of days in months. As for me, better than setting width to 30 (because we have months with 31 and 28 days) is converting dates to factor as lukeA adviced – inscaven Oct 12 '15 at 11:22
  • I try `width=30` , but in some months i get text not in the middle( look not pretty). @lukeA Its realy good( you can post it as answer), thanks! – Batanichek Oct 12 '15 at 11:35

1 Answers1

10

You could try

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")
lukeA
  • 53,097
  • 5
  • 97
  • 100