如何解决更改人口金字塔中标签的位置 (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 函数)。 有没有人知道如何解决这个问题?谢谢!
解决方法
这有效:
geom_text(aes(hjust = ifelse(Geschlecht == "Bock",1,0))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。