This practical focuses on building scatterplots with ggplot2, then splitting plots into subplots with facets.
All datasets used here are built into R packages.
Create a scatterplot
- Load the
tidyverse package and the starwars dataset.
library(tidyverse)
data(starwars)
- Create a scatterplot of
mass (x-axis) against height (y-axis).
starwars |>
ggplot() +
aes(x = mass, y = height) +
geom_point()
Warning: Removed 28 rows containing missing values or values outside the scale range
(`geom_point()`).
- Remove the outlying point and redraw the plot.
starwars |>
filter(mass < 1000) |>
ggplot() +
aes(x = mass, y = height) +
geom_point()
- Color the points by
homeworld.
starwars |>
filter(mass < 1000) |>
ggplot() +
aes(x = mass, y = height) +
geom_point(aes(color = homeworld))
- Add a line-of-best-fit.
starwars |>
filter(mass < 1000) |>
ggplot() +
aes(x = mass, y = height) +
geom_point(aes(color = homeworld)) +
geom_smooth(method = "lm") +
theme(legend.position = "none")
`geom_smooth()` using formula = 'y ~ x'
Facets with facet_wrap
- Load the
mtcars dataset.
- Create a scatterplot of
wt against mpg.
- Color the points by
cyl.
- Add a line-of-best-fit.
- Produce separate plots for automatic and manual cars (
am).
mtcars |>
ggplot() +
aes(x = wt, y = mpg) +
geom_point(aes(color = factor(cyl))) +
geom_smooth(method = "lm") +
facet_wrap(~ am)
`geom_smooth()` using formula = 'y ~ x'