【问题标题】:Change position of labels in population pyramid (ggplot2)更改人口金字塔中标签的位置(ggplot2)
【发布时间】:2021-04-20 17:25:45
【问题描述】:

我在 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

【问题讨论】:

  • 尝试使用geom_text(aes(label = ..., hjust = ifelse(Geschlecht == "Bock", 1, 0)) 或其他方式,应将标签与条形左对齐或右对齐。 (:顺便说一句:山羊的人口金字塔?很有趣。(;
  • hjust = 'outside' 可能有效。

标签: r ggplot2 label population


【解决方案1】:

这行得通:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 2020-12-16
    • 2013-03-26
    相关资源
    最近更新 更多