3
votes

I can't figure out how to display labels centered on each dodged bar in a barplot in ggplot2.

I know that I can dodge the bars using position = "dodge" and I know that in order for the labels to show up centered on each bar I need to add position = position_dodge(width = 1) in the geom_text() or geom_label() command.

But for some reason it doesn't work (see Figure below). I also added my data and code.

df <- structure(list(Measure = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1988", 
"2017"), class = "factor"), Province = structure(c(1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 
9L, 10L), .Label = c("BC", "AB", "SK", "MB", "ON", "QC", "NB", 
"PE", "NS", "NL"), class = "factor"), Value = c(363L, 61L, NA, 
69L, NA, NA, 127L, 12L, 92L, 18L, 178L, 29L, 41L, 92L, 284L, 
1019L, 267L, 27L, 77L, 22L)), .Names = c("Measure", "Province", 
"Value"), row.names = 41:60, class = "data.frame")

ggplot(df, aes(x=Province, y=Value)) + geom_bar(aes(fill=Measure), position="dodge", 
stat="identity") + geom_label(aes(label=Value), position = position_dodge(width=1))

enter image description here

3

3 Answers

3
votes

I just realized (thanks to @aelwan answer) that the only thing I had to do is adding group=Measure in the aes() function, i.e.

ggplot(df, aes(x=Province, y=Value, group=Measure)) +
       geom_bar(aes(fill=Measure),position="dodge", stat="identity") + 
       geom_label(aes(label=Value),position = position_dodge(width=1))

That gives:

enter image description here

2
votes

Try this

ggplot(df, aes(x=Province, y=Value, group = Measure)) + 
  geom_col(aes(fill=Measure), 
           position ="dodge", width = 0.4)+
  geom_text(aes(label= Value,
                group = Measure
  ),vjust= 0,  position = position_dodge(0.4) , color="black" )

enter image description here

0
votes

This is a late answer, but the geom_text is not perfectly centered over the bars. One way to fix this is by also specifying the width of the bars position=position_dodge(width = 1).

geom_bar(aes(fill=Measure),position=position_dodge(width = 1), stat="identity")