Choose one or two of your previous plots, and give the scales a proper name.
Hint: Use one or more scale_...()
functions or the labs()
function.
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. We recommend to stick with the explicit versions.
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.
Choose an appealing color 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, mapping = aes(x = displ, y = hwy)) +
geom_jitter(mapping = aes(color = class)) +
scale_x_continuous(name = "Displacement") +
scale_y_continuous(name = "Fuel economy [miles per gallon]") +
scale_color_viridis_d(name = "Car class", option = "A")
Practice Markdown: Create sections, subsections, item lists, emphasized and bold text.
Copyright © 2019 Kirill Müller. Licensed under CC BY-NC 4.0.