如何在ggplot2 :: position_stack中缩放距离?

时间:2018-04-30 14:07:56

标签: r ggplot2 scale

我想绘制一个人口金字塔,其标签旁边是ggplot的堆积条形图。我使用position_stack(vjust=1.3)将标签显示在' top'旁边。使用下面的代码,但我不明白该命令如何缩放标签的位置。

library(tidyverse)

data.frame(
  sex = c("F", "F", "F", "F", "F", "F", "F", "F", "M", "M", "M", "M", "M", "M", "M", "M"), 
  ag = c("0-9", "10-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70+"), 
  n = c(-0.21, -0.12, -0.09, -0.03, -0.04, -0.01, 0, 0, 0.22, 0.11, 0.06, 0.04, 0.02, 0.03, 0.01, 0),
  stringsAsFactors = F
) %>% 
  ggplot(aes(x=ag, y = n, fill=sex)) +
  geom_col() +
  scale_fill_brewer("",labels = c("Women", "Men"), palette = "Set1") +
  coord_flip() +
  geom_text(data = . %>% dplyr::filter(sex == "M"),
            aes(label = n),
            position=position_stack(vjust=1.3)) +
  geom_text(data = . %>% dplyr::filter(sex == "F"),
            aes(label = n),
            position=position_stack(vjust=-0.3)) 

在结果图中,标签与条形的上边缘不等距。我希望标签在每个栏旁边都能整齐地显示出来。 enter image description here

1 个答案:

答案 0 :(得分:3)

您可以尝试position_nudge

   df %>% 
{ggplot(data=.,aes(x=ag, y = n, fill=sex,label = n)) +
  geom_col() +  
  geom_text(position = position_nudge(y = ifelse(.$sex == "F", -0.02, 0.02)))+
  coord_flip()}

enter image description here

相关问题