122

I've found this, How to put labels over geom_bar in R with ggplot2, but it just put labels(numbers) over only one bar.

Here is, let's say, two bars for each x-axis, how to do the same thing?

My data and code look like this:

dat <- read.table(text = "sample Types Number
sample1 A   3641
sample2 A   3119
sample1 B   15815
sample2 B   12334
sample1 C   2706
sample2 C   3147", header=TRUE)

library(ggplot2)
bar <- ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
  geom_bar(position = 'dodge') + geom_text(aes(label=Number))

Then, we'll get: enter image description here

It seems that the number texts are also positioned in the "dodge" pattern. I've searched geom_text manual to find some information, but cannot make it work.

Suggestions?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Puriney
  • 2,417
  • 3
  • 20
  • 25

2 Answers2

180

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

rcs
  • 67,191
  • 22
  • 172
  • 153
  • 5
    (+1) You could also add `vjust = -0.5` after the `position()` statement so that the values are placed just above the bars. – smillig Aug 18 '12 at 15:09
  • 3
    Great thanks, by the way, the code suggests setting `ymax`, so `aes(x=Types, y=Number, fill=sample, ymax = 16000)`, will produce wider upper area for y-axis, so that 15815 will get better shown. – Puriney Aug 19 '12 at 03:00
  • I get this error: Error: stat_count() must not be used with a y aesthetic. – userJT Mar 28 '17 at 21:16
  • 3
    this answer has newer syntax http://stackoverflow.com/questions/33079500/geom-text-with-dodged-barplot?noredirect=1&lq=1 – userJT Mar 28 '17 at 21:21
  • How can I change the orientation of the label in the case the histogram was rotated horizontally? – Seymour Apr 18 '18 at 21:11
  • 3
    @Seymour `geom_text(..., angle=-90)` – rcs Apr 19 '18 at 09:51
  • This works also with `geom_label`: `geom_label(position=position_dodge(width=0.9))`. But why the 0.9? – Rafs May 11 '21 at 16:24
5

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
 geom_bar(position = "dodge", stat = 'identity') +
 geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)
Community
  • 1
  • 1
matmat
  • 875
  • 8
  • 11