2

my data looks something like this:

structure(list(region1 = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 6L, 6L, 
6L, 6L, 7L, 7L, 7L, 7L), .Label = c("Location1", "Location2", 
"Location3", "Location4", "Location5", "Location6", 
"OTHERS"), class = "factor"), startYear = c(2016, 2017, 2018, 
2019, 2016, 2017, 2018, 2019, 2016, 2017, 2018, 2019, 2016, 2017, 
2018, 2019, 2016, 2017, 2018, 2019, 2016, 2017, 2018, 2019, 2016, 
2017, 2018, 2019), n = c(322L, 697L, 620L, 849L, 832L, 541L, 
868L, 687L, 117L, 706L, 613L, 689L, 733L, 445L, 150L, 220L, 936L, 
277L, 195L, 751L, 80L, 851L, 38L, 179L, 808L, 635L, 304L, 617L
)), row.names = c(NA, -28L), class = c("data.table", "data.frame"
))

and i am trying to create a grouped bar chart with text labels above every bar. Here is how:

  # create grouped barchart 
  ggplot(dataExample, aes(x = startYear, y = n)) +
    geom_col(aes(color = as.factor(region1), 
                 fill = as.factor(region1)),
             position = position_dodge(0.8), width = 0.7)+
    geom_text(aes(startYear, label = n),
            position = position_dodge(0.8), width = 0.7)

Unfortunatelly I cannot get my labels to allign. Here is what i am getting:

enter image description here

How can i adjust the position, such that the labels are where they are supposed to be?

Nneka
  • 1,764
  • 2
  • 15
  • 39

1 Answers1

0

You need to group the geom_text aesthetic:

ggplot(dataExample, aes(x = startYear, y = n)) +
    geom_col(aes(color = as.factor(region1), 
                 fill = as.factor(region1)),
             position = position_dodge(0.8))+
    geom_text(aes(startYear, label = n, group=as.factor(region1)),
            position = position_dodge(0.8))

(note that I deleted the witdh options that caused an error)

Claudio
  • 1,229
  • 6
  • 11