2013-09-25 68 views
10

我试图把标签上使用这种方法堆叠条形图(不过,如果现在有一个更好的方法我愿意什么都):中心标签堆叠栏(计数)GGPLOT2

Showing data values on stacked bar chart in ggplot2

这里是我的原创情节:

dat <- data.frame(with(mtcars, table(cyl, gear))) 

ggplot(dat, aes(x = gear, fill = cyl)) + 
    geom_bar(aes(weight=Freq), position="stack") + 
    geom_text(position = "stack", aes(x = gear, y = Freq, 
     ymax = 15, label = cyl), size=4) 

enter image description here

这是我尝试在每个填充部分居中标签:

dat2 <- ddply(dat, .(cyl), transform, pos = cumsum(Freq) - 0.5*Freq) 

library(plyr) 
ggplot(dat2, aes(x = gear, fill = cyl)) + 
    geom_bar(aes(weight=Freq), position="stack") + 
    geom_text(position = "stack", aes(x = gear, y = pos, 
     ymax = 15, label = cyl), size=4) 

enter image description here

我怎样才能居中标签中的每个填充部分?

回答

10

有一些外来ddply动作发生的事情与这一个,因为我知道我想要的解决方案,但遇到了麻烦保持与位置对齐的频率,但我认为该算法用于查找组中点值得发帖:

group_midpoints = function(g) { 
    cumsums = c(0, cumsum(g$Freq)) 
    diffs = diff(cumsums) 
    pos = head(cumsums, -1) + (0.5 * diffs) 
    return(data.frame(cyl=g$cyl, pos=pos, Freq=g$Freq)) 
} 

dat3 = ddply(dat, .(gear), group_midpoints) 

ggplot(dat3, aes(x = gear, fill = cyl)) + 
    geom_bar(aes(weight=Freq), position="stack") + 
    geom_text(position = "identity", aes(x = gear, y = pos, ymax = 15, label = cyl), size=4) 

enter image description here

+0

完美。我靠近但不完全。 +1 –