0

I'm trying to produce a plot of sums of a particular variable over time by facet in ggplot. I'm working on a school assignment, so I will use the built-in mpg data set for this question rather than the actual data.

One task is to plot the displacement by year for each class in mpg. The code

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

produces the desired result. But for the next question, I have to produce nearly the same plot but plot the sum of the displacements by year for each class, and I can't seem to do it. I've tried variations of tapply to no avail. I had hoped that

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

would do it but it did not.

help-info.de
  • 6,695
  • 16
  • 39
  • 41
Rob Creel
  • 323
  • 1
  • 8

2 Answers2

1

You could consider using stat_summary and skipping qplot:

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

enter image description here

Heroka
  • 12,889
  • 1
  • 28
  • 38
0

We could try this with dplyr too:

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

enter image description here

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63