2016-06-10 148 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