【问题标题】:Aggregating data with ggplot使用 ggplot 聚合数据
【发布时间】:2016-06-10 13:54:47
【问题描述】:

让我们以mpg 数据集为例,特别是classcyl 列。我可以看到每个 class 有多少条目,并根据 cyl 值区分填充颜色:

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_summarylink
  • @user3631369 我现在正在玩它,但我没有得到结果。我无法聚合 cyl 字段。

标签: r plot ggplot2


【解决方案1】:

我们可以将您的公式直接插入stat_summary() 以生成所需的结果,无需中间步骤:

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

【讨论】:

  • 有没有办法传递fun.y一个聚合函数,它基于data.frame中的其他变量? (所以,我可以计算每个组内的总和 - 不知何故我无法让它工作......)
  • 你能举个例子吗?也许问一个新问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 2019-05-20
  • 1970-01-01
  • 2012-08-09
相关资源
最近更新 更多