我们以mpg
数据集为例,具体为class
和cyl
列。我可以看到有多少项都在那里,每单class
,并分化基础上,共青团值填充颜色:使用ggplot汇总数据
library(ggplot2)
p <- ggplot(mpg)
p <- p + geom_bar(mapping=aes(x=class, fill=factor(cyl)), position=position_dodge())
print(p)
我想看到的,虽然是平均条目数(每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')
这让我所需的输出:
然而,鉴于GGPLOT2多么强大,我想知道这是否可以通过ggplot函数。我想这涉及到使用特定的stat
(可能与group=cyl
?),但我无法。
给看看'stat_summary' [链接](HTTP://docs.ggplot2 .org/current/stat_summary.html) – user3631369
@ user3631369我正在玩它,但我没有得到结果。我无法聚集在cyl字段。 – natario