Naming scales

Choose one or two of your previous plots, and give the scales a proper name.

Hint: Use one or more scale_...() functions.

ggplot(
  data = mpg,
  mapping = aes(x = displ, y = hwy, color = factor(year))
) +
  geom_point() +
  geom_smooth(method = "lm") +
  facet_wrap(~class) +
  scale_x_continuous(name = "___") +
  scale_y_continuous(name = "___") +
  scale_color_discrete(name = "___")

► Solution: Reusing a plot from the previous exercise:

ggplot(data = mpg) +
  geom_point(
    mapping = aes(x = displ, y = hwy, color = factor(year))
  ) +
  geom_smooth(
    mapping = aes(x = displ, y = hwy, color = factor(year)),
    method = "lm"
  ) +
  facet_wrap(~class) +
  scale_x_continuous(name = "Displacement") +
  scale_y_continuous(name = "Fuel economy [miles per gallon]") +
  scale_color_discrete(name = "Year")

There exist shortcuts xlab() and ylab() for x and y labels, but not for color or fill. I recommend to stick with the explicit versions.

Changing scales twice

What happens if you call the same scale_...() function twice in a plot?

► Solution: A warning occurs:

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy)) +
  scale_x_continuous(name = "Displacement") +
  scale_x_continuous(name = "Displacement")
## Scale for 'x' is already present. Adding another scale for 'x', which
## will replace the existing scale.

ColorBrewer scales

Add an overview over all available colorblind friendly Brewer scales to your rmarkdown document.

Hint: Insert a code chunk containing RColorBrewer::display.brewer.all(colorblindFriendly = TRUE)

► Solution:

RColorBrewer::display.brewer.all(colorblindFriendly = TRUE)

A better scale for car class

Choose an appealing scale for one of your plots that use the “color” or “fill” aesthetics. Apply it with scale_..._brewer("<name>", palette = "<palette>")

Hint: Use scale_..._distiller() if you have mapped a continuous variable.

► Solution:

ggplot(data = mpg) +
  geom_jitter(mapping = aes(x = displ, y = hwy, color = class)) +
  scale_x_continuous(name = "Displacement") +
  scale_y_continuous(name = "Fuel economy [miles per gallon]") +
  scale_color_brewer(name = "Car class", palette = "Set2")

Practice

Practice Markdown: Create sections, subsections, item lists, emphasized and bold text, … .

Copyright © 2018 Kirill Müller. Licensed under CC BY-NC 4.0.