2017-01-05 12 views
3

我有一个充满条形图这样如何在带有%标签的填充条的分面ggplot中显示'total'?

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) 

如果没有显示在小面它的作品总。但由于用于显示%数据标签的方法(我想知道是否有更好的方法),总的方面会变得混乱。有什么建议?谢谢。

+0

你期望的利润率是在范围[0,1]? – Alex

+0

yup,因为在所有填写到100% – santoku

回答

5

我正确安排了标签,并事先定义了边距图。我想这是你所期望的输出。我无法弄清楚是否有办法通过来实现这一点。

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

+0

谢谢。我在想像类似grid.arrange的东西。似乎很难在填充栏上显示标签。 – santoku

相关问题