Position geom_text on dodged barplot

Is this what you want?

library(ggplot2)

ggplot(bar) + 
  geom_col(aes(variable, `(all)`, fill = ustanova), position = "dodge") +
  geom_text(aes(variable, `(all)`, label = sprintf("%2.1f", `(all)`), group = ustanova), 
            position = position_dodge(width = .9)) +
  coord_flip()

The key is to position = position_dodge(width = .9) (where .9 is the default width of the bars) instead of position = "dodge", which is just a shortcut without any parameter. Additionally you have to set the group=ustanova aesthetic in geom_text to dodge the labels by ustanova (A second option would be to make fill = ustanova a global aesthetic via ggplot(bar, aes(fill = ustanova))


In ggplot2_2.0.0 you find several examples in ?geom_text on how to position geom_text on dodged or stacked bars (the code chunk named “# Aligning labels and bars"). The Q&A What is the width argument in position_dodge? provides a more thorough description of the topic.

Leave a Comment