更改人口金字塔中标签的位置 (ggplot2)

我在 R Studio 中标记人口金字塔时遇到问题。我想在两个不同的方向上调整标签的位置,这取决于它们在哪一边。更准确地说,我希望左侧(男性)的值更靠左一点,因此它们相邻到左侧条形,右侧(女性)的值有点更靠右,因此它们与右侧的条相邻。

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)

我已经尝试用 position_stack 和 position_nudge 解决它,但我无法弄清楚如何根据性别在两个不同的方向上移动值(尝试使用 ifelse 函数)。 有没有人知道如何解决这个问题?谢谢!

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

nzjnzj 回答:更改人口金字塔中标签的位置 (ggplot2)

这有效:

geom_text(aes(hjust = ifelse(Geschlecht == "Bock",1,0))
本文链接:https://www.f2er.com/1097998.html

大家都在问