0

I am working my way through R4DS, and am trying to tweak my solution for 3.8.1 exercise 4. I ended up with the following code:

ggplot(data = mpg, mapping = aes(x = manufacturer, y = hwy/cty, colour = year)) +
  geom_boxplot() + coord_flip()

This does not work as intended. But when I replace colour = year with colour = drv, I get a nice grouped boxplot. Why can’t this be done with year?

RStudio 0.99.902; ggplot2 v. 2.1.0.

Canned Man
  • 734
  • 1
  • 7
  • 26

1 Answers1

1

Seems to work when you write it into geom_boxplot.

ggplot(data = mpg, mapping = aes(x = manufacturer, y = hwy/cty)) +
geom_boxplot(aes(colour=factor(year))) + coord_flip()
Micky
  • 190
  • 11
  • As they noted above, the grouping variable needs to be a factor. – Micky Oct 10 '16 at 13:17
  • Your solution works just as I intended. Could you, in your answer include an explanation on what factor does to the variable? – Canned Man Oct 11 '16 at 12:13
  • 1
    This is a good explanation on how grouping works in ggplot ... http://stackoverflow.com/questions/10357768/plotting-lines-and-the-group-aesthetic-in-ggplot2 – Micky Oct 12 '16 at 07:46