geom_text与堆叠的geom_bar-如何使其兼容?

时间:2018-08-08 15:27:26

标签: r ggplot2

data <- nycflights13::flights %>% 
    filter(row_number() < 51) %>% 
    select(carrier, distance) %>% 
    group_by(carrier) %>% 
    summarise(distance = sum(distance)) %>% 
    mutate(prop = distance/sum(distance))

使用上面的数据,我想堆叠一个geom_bar,然后用geom_text添加百分比值。但是,geom_text的标签并不指向geom_bar的后续层(请参见下文)。

ggplot(data, aes(x = 1, y = prop)) + geom_bar(aes(fill = carrier), stat = 'identity') +
    coord_flip() + theme_void() + theme(legend.position = 'top') +
    labs(fill = '') +
    guides(fill = guide_legend(nrow = 1)) + 
    scale_fill_viridis_d() + 
    geom_text(aes(label = paste0(round(prop, 3) * 100,"%")), 
                 position = position_stack(vjust = 0), size = 2)

enter image description here

顺便说一句。第二个问题是,情节上方的图例与文档顶部之间没有空白-我认为问题与theme_void的使用有关,但是如何在图例之前稍作空白?

1 个答案:

答案 0 :(得分:1)

data <- nycflights13::flights %>% 
  filter(row_number() < 51) %>% 
  select(carrier, distance) %>% 
  group_by(carrier) %>% 
  summarise(distance = sum(distance)) %>% 
  arrange(desc(carrier)) %>%
  mutate(prop = distance/sum(distance),
         pos = cumsum(prop)-prop/2) 


ggplot(data, aes(x = 1, y = prop)) + geom_bar(aes(fill = carrier), stat = 'identity')  +
  coord_flip() + theme_void() + 
  theme(legend.position = 'top',
        plot.margin = margin(20,1,1,1,'pt')) +
  labs(fill = '') +
  guides(fill = guide_legend(nrow = 1)) + 
  scale_fill_viridis_d() + 
  geom_text(aes(x= 1, y= pos,label = paste0(round(prop, 3) * 100,"%")), size = 2)

您可以使用plot.margin来解决页边距问题,也可以使用pos = cumsum(prop)-prop/2来手动计算标签的正确y位置以将标签放置在条的中间。由于您的数据在图中按字母顺序排列,因此在计算位置之前,我还必须对数据进行排序。