2016-06-10 147 views
9

我們以mpg數據集爲例,具體爲classcyl列。我可以看到有多少項都在那裏,每單class,並分化基礎上,共青團值填充顏色:使用ggplot彙總數據

library(ggplot2) 
p <- ggplot(mpg) 
p <- p + geom_bar(mapping=aes(x=class, fill=factor(cyl)), position=position_dodge()) 
print(p) 

enter image description here

我想看到的,雖然是平均條目數(每class),每個不同的值cyl。基本上,如果你看看上面的情節,我想要一個單一的酒吧,其高度應該是該類別的彩色條的平均高度。

我能夠通過預處理數據幀得到這樣的結果,如:

df <- aggregate(formula=cyl~class, data=mpg, FUN=function(x) { length(x)/length(unique(x)) }) 
p <- ggplot(df) 
p <- p + geom_bar(mapping=aes(x=class, y=cyl), stat='identity') 
p <- p + ylab('average count') 

這讓我所需的輸出

enter image description here

然而,鑑於GGPLOT2多麼強大,我想知道這是否可以通過ggplot函數。我想這涉及到使用特定的stat(可能與group=cyl?),但我無法。

+0

給看看'stat_summary' [鏈接](HTTP://docs.ggplot2 .org/current/stat_summary.html) – user3631369

+0

@ user3631369我正在玩它,但我沒有得到結果。我無法聚集在cyl字段。 – natario

回答

13

我們可以將你的公式直入stat_summary()產生無中間步驟所需的結果:

library(ggplot2) 
ggplot(mpg) + 
    stat_summary(aes(x = class, y = cyl), 
       fun.y = function(x) length(x)/length(unique(x)), 
       geom = "bar") 

enter image description here

+0

有沒有辦法將'fun.y'傳遞給聚合函數,即基於data.frame中的其他變量? (所以,我可以計算每個組內的總和 - 不知何故,我無法得到這個工作...) –

+0

你能舉個例子嗎?也許問一個新問題 – mtoto