ggplot 数据总和图的方面,而不是数据本身

ggplot facets of plots of sum of data, rather than data itself

我正在尝试在 ggplot 中按方面生成特定变量随时间变化的总和图。我正在做一项学校作业,所以我将使用内置的 mpg 数据集来解决这个问题,而不是实际数据。

一项任务是以 mpg 为单位按年份绘制每个 class 的排量。代码

qplot(data = mpg, year, displ, facets = . ~ class)

产生了想要的结果。但是对于下一个问题,我必须制作几乎相同的图,但是为每个 class 绘制每年位移的 sum,但我似乎做不到.我尝试了 tapply 的变体,但无济于事。我曾希望

qplot(data = mpg, year, sum(displ), facets = . ~ class)

会做但没有做。

您可以考虑使用 stat_summary 并跳过 qplot:

ggplot(mpg, aes(x=year, y = displ)) +
  stat_summary(fun.y="sum", geom="point") + facet_grid(.~class)

我们也可以用 dplyr 试试这个:

library(dplyr)
mpg %>% group_by(year, class) %>% summarise(displ=sum(displ)) %>% 
  ggplot(aes(year, displ)) + geom_point() + facet_grid(~class)