2

I'm reading Hadley Wickham's ggplot2 book and would like to get comments on my solution to one of the exercises:

Section 6.5.1
Exercise 1

The following code creates two plots of the mpg dataset. Modify the code so that the legend and axes match, without using facetting!

fwd <- subset(mpg, drv == "f")
rwd <- subset(mpg, drv == "r")
ggplot(fwd, aes(displ, hwy, colour = class)) + geom_point()
ggplot(rwd, aes(displ, hwy, colour = class)) + geom_point()

enter image description here Here's my solution:

ggplot(fwd, aes(displ, hwy, colour = class)) +
  geom_point() +
  lims(x = c(0, 7), y = c(0, 45)) +
  geom_point(aes(colour = class), alpha = 0, data = mpg) +
  guides(colour = guide_legend(override.aes = list(alpha = 1)))

ggplot(rwd, aes(displ, hwy, colour = class)) +
  geom_point() +
  lims(x = c(0, 7), y = c(0, 45)) +
  geom_point(aes(colour = class), alpha = 0, data = mpg) +
  guides(colour = guide_legend(override.aes = list(alpha = 1)))

enter image description here I feel like my idea is smart, but it wouldn't be efficient for larger datasets. Is there a more direct way to solve this problem? Or is this what the exercise is aiming at?

1
  • 1
    Problems of your solution: It impacts the axis limits. It creates invisible points. Those clutter the output file and some devices have problems with alpha transparency. Conceptually, adding new data to achieve a different presentation of a dataset can't be the solution within ggplot2. Such a solution doesn't adhere to the Grammar of Graphics.
    – Roland
    Jan 4, 2017 at 7:38

1 Answer 1

2

Just use drop = FALSE to keep all the factor levels.

mpg$class <- as.factor(mpg$class) # convert to factor
fwd <- subset(mpg, drv == "f")
rwd <- subset(mpg, drv == "r")
ggplot(fwd, aes(displ, hwy, colour = class)) + geom_point() + scale_colour_discrete(drop=FALSE)
ggplot(rwd, aes(displ, hwy, colour = class)) + geom_point() + scale_colour_discrete(drop=FALSE)

enter image description here

1
  • Thanks! I knew there'd be something more straightforward.
    – Novice
    Jan 4, 2017 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.