2013-09-25 129 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 –