Practical 1

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

  1. Load the tidyverse package and the starwars dataset.
library(tidyverse)
data(starwars)
  1. 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()`).

  1. Remove the outlying point and redraw the plot.
starwars |>
  filter(mass < 1000) |>
  ggplot() +
  aes(x = mass, y = height) +
  geom_point()

  1. Color the points by homeworld.
starwars |>
  filter(mass < 1000) |>
  ggplot() +
  aes(x = mass, y = height) +
  geom_point(aes(color = homeworld))

  1. 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

  1. Load the mtcars dataset.
data(mtcars)
  1. Create a scatterplot of wt against mpg.
  2. Color the points by cyl.
  3. Add a line-of-best-fit.
  4. 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'