Introduction to ggplot2 - Solutions

Exercise A - (2 min)

  1. Using the preceding slide as a template, make a scatterplot with pop on the x-axis and lifeExp on the y-axis, based on gapminder_2007.
  2. Repeat the preceding but with gdpPercap on the y-axis.

Solution

# Prep
library(gapminder)
library(tidyverse)

gapminder_2007 <- gapminder %>% 
  filter(year == 2007)

# Part 1
gapminder_2007 |> 
ggplot(aes(x = gdpPercap, y = lifeExp)) + 
  geom_point()

# Part 2
gapminder_2007 |> 
ggplot(aes(x = pop, y = gdpPercap)) + 
  geom_point()

Exercise B - (5 min)

Label your axes and give each plot a title!

  1. Make a scatterplot with the log base 10 of pop on the x-axis and lifeExp on the y-axis using gapminder_2007.
  2. Figure out how to make a plot with the y-axis on the log scale. Then repeat my plot from the previous slide with gdpPercap in levels and lifeExp in logs.
  3. Repeat 2 but with both axes on the log scale.

Solution

# Part 1
gapminder_2007 |> 
  ggplot(aes(x = pop, y = lifeExp)) +
  geom_point() +
  scale_x_log10()

# Part 2
gapminder_2007 |> 
  ggplot(aes(x = gdpPercap, y = lifeExp)) +
  geom_point() +
  scale_y_log10()

# Part 3
gapminder_2007 |> 
  ggplot(aes(x = gdpPercap, y = lifeExp)) +
  geom_point() + 
  scale_x_log10() + 
  scale_y_log10()