ggplot label bars in grouped bar plot

Add fill = Country to the geom_text and clearly specify dodging width to make sure both the bars and the labels are aligned:

library(data.table)
library(ggplot2)

# Fictional sample data
x <- data.table(Year = c(2010,1970,1980,1970,1950,1950,1980,1980,2010), 
                Country = c("St. Vincent and the Grenadines", "Ukraine", "Yemen", "Romania", "Cyprus", "Netherlands",
                            "Mauritania", "Niger", "Grenada"), Count = c(5,2,1,4,7,6,4,1,2))

p <- ggplot(x[which(x$Count>0)], aes(Year, Count)) + geom_bar(aes(fill = Country), position = position_dodge(9), stat="identity")
p + theme(legend.position="none") + scale_x_discrete(limits=unique(x$Year)) + geom_text(position = position_dodge(width= 9), aes(y=Count+0.25, fill=Country, label=Country, hjust=0), angle=90)

(Note: I also adjusted the position with hjust)

enter image description here


You can try

library(ggplot2)
ggplot(a,aes(factor(Year), Count, fill =Country, label =Country)) + 
  geom_col(position = position_dodge2(width = 0.9, preserve = "single"), show.legend = F) +
  geom_text(position = position_dodge2(width = 0.9, preserve = "single"), angle = 90, vjust=0.25, hjust=0) +
  ylim(0,40)

enter image description here

data

a <- read.table(text="Year  Country Count
2010    St.VincentandtheGrenadines  0
1970    Ukraine 0
1980    Yemen   1
1970    Romania 0
1950    Cyprus  0
1950    Netherlands 0
1980    Mauritania  0
1980    Niger   0
2010    Grenada 2
1970    Israel  6
1990    Suriname    0
1990    Singapore   1
1960    Russia  0
1970    Barbados    0
1950    Panama  0
2010    Mali    3
1980    Greece  11
2010    Venezuela   15
2000    Malawi  9
2000    Jamaica 34
1970    Angola  0
1990    Lebanon 0
1980    CentralAfricanRepublic  0
1950    UnitedKingdom   1
2010    Iceland 26", header=T)

Tags:

R

Ggplot2