如何展示'总计'在带有%标签的填充栏的刻面ggplot中?

时间:2017-01-05 13:49:38

标签: r ggplot2 bar-chart facet-grid

我有一个像这样的填充条形图

library(dplyr)
library(ggplot2)

df <- data.frame(facet=c(rep(1,6),rep(2,6)),type=rep(c('a','b','c'),2), subtype=c('x','y'), value=c(10,20,30,10,50,70))

df %>% group_by(type, facet) %>% 
mutate(pct=value/sum(value)) %>%
mutate(pos=cumsum(pct) - (0.5 * pct)) %>%
ggplot(aes(type, pct, fill=subtype)) + geom_bar(stat='identity') +
geom_text(aes(label=paste0(round(100*pct, 0), '%'),y=pos)) +   facet_grid(.~facet, margins=TRUE)

如果没有在整像中显示总数,则可行。但是由于用于显示%data标签的方法(我想知道是否有更好的方法),总方面会搞砸。任何建议?感谢。

1 个答案:

答案 0 :(得分:5)

我正确安排了标签并事先定义了边距图。我猜这是你期望的输出。我无法弄清楚是否有办法通过facet_grid(., margin = TRUE)来实现这一目标。

df <- data.frame(facet=c(rep(1,6),rep(2,6)),type=rep(c('a','b','c'),2),
                 subtype=c('x','y'), value=runif(12, 0, 100))

df1  <- df %>% 
        arrange(desc(subtype)) %>% 
        mutate(facet = factor(facet, levels = c("1", "2", "(all)"))) %>%
        group_by(type, facet) %>% 
        mutate(pct=value/sum(value),
               pos=cumsum(pct) - (0.5 * pct)) 

df2 <- df1 %>%
      group_by(type, subtype) %>%
      summarise(facet = factor("(all)", levels = c("1", "2", "(all)")),
                pct = sum(pct)/2,
                pos = sum(pos/2))  

  bind_rows(df1, df2) %>%
  ggplot(aes(type, pct, fill=subtype)) + 
  geom_bar(stat='identity', position = "stack") +
  geom_text(aes(label=paste0(round(100*pct, 0), '%'),y=pos)) +   
  facet_grid(.~facet)

enter image description here