How to put labels over geom_bar for each bar in R with ggplot2

RGgplot2Bar Chart

R Problem Overview


I've found this, https://stackoverflow.com/questions/6455088/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?

R Solutions


Solution 1 - R

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

Solution 2 - R

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPurineyView Question on Stackoverflow
Solution 1 - RrcsView Answer on Stackoverflow
Solution 2 - RmatmatView Answer on Stackoverflow