Search code examples
rggplot2labelpopulation

Change position of labels in population pyramid (ggplot2)


I'm having a problem with labeling my population pyramid in R Studio. I would like to adjust the positions of the labels in two different directions, depending on which side they are at. More precisely, I want the values on the left side (males) to be a bit more to the left so they are adjacent to the left bars, and the values on the right side (females) a bit more to the right so they are adjacent to the right bars.

This is my data and the code I have so far:
#   Geschlecht      Alter Anzahl     Prozent
#1        Bock        0.5      6 0.006276151
#2        Bock        1.5    172 0.179916318
#3        Bock       10.5     23 0.024058577
#4        Bock       11.5      8 0.008368201
#5        Bock       12.5     14 0.014644351
#Translation column names: Sex, Age, Count, Percentage

ggplot(Verteilung,aes(x = Alter,
                       y = ifelse(Geschlecht == 'Bock', -Anzahl, Anzahl),
                       fill = Geschlecht,
                       label = Anzahl)) +
  geom_bar(stat = 'identity') +
  scale_y_continuous(name = 'Anzahl', labels = abs, breaks = seq(-200,200,10)) +
  scale_x_discrete(name = 'Alter', limits = c('1.5','2.5','3.5','4.5','5.5','6.5','7.5','8.5','9.5',
'10.5','11.5','12.5','13.5','14.5','15.5','16.5','17.5','18.5','19.5')) +
  coord_flip() +
  theme_minimal() +
  ggtitle('Zusammensetzung Verteilung nach Alter und Geschlecht') +
  scale_fill_manual(values = c('steelblue1', 'hotpink1')) +
  geom_text(aes(label = Anzahl), size = 4)

I've tried solving it with position_stack and position_nudge but I couldn't figure out how to shift the values in two different directions depending on the sex (tried with ifelse function). Does anyone have an idea on how to solve this? Thank you!

My current population pyramid. I would like the labels to be positioned adjacent to the bars, i.e. a bit more to the left on the left side, and a bit more to the right on the right side


Solution

  • This worked:

    geom_text(aes(hjust = ifelse(Geschlecht == "Bock", 1, 0))