Part 15 Activity: Build some plots!

15.1 Make a Line Chart

The following code makes a data frame called mauna that contains time series data of CO\(_2\) concentrations collected monthly at the Mauna Loa vocanic observation station.

Execute this code to store the data in mauna:

(mauna <- tsibble::as_tsibble(co2) |> 
   rename(month = index, conc = value))
#> # A tsibble: 468 x 2 [1M]
#>       month  conc
#>       <mth> <dbl>
#>  1 1959 Jan  315.
#>  2 1959 Feb  316.
#>  3 1959 Mar  316.
#>  4 1959 Apr  318.
#>  5 1959 May  318.
#>  6 1959 Jun  318 
#>  7 1959 Jul  316.
#>  8 1959 Aug  315.
#>  9 1959 Sep  314.
#> 10 1959 Oct  313.
#> # … with 458 more rows

Produce a line chart showing the concentration over time. Specifically, the plot should have the following grammar components:

Grammar Component Specification
data mauna
aesthetic mapping x: month, y: conc
geometric object lines
scale yearmonth
statistical transform none
coordinate system rectangular
faceting none

Fill in the blanks to obtain the plot:

ggplot(FILL_THIS_IN) +
  aes(FILL_THIS_IN, FILL_THIS_IN)
  FILL_THIS_IN() + 
  tsibble::scale_x_yearmonth()

15.2 Make a Scatterplot

Use the palmerpenguins::penguins data to make a scatterplot with the following specifications:

Grammar Component Specification
data palmerpenguins::penguins
aesthetic mapping x: body_mass_g, y: bill_depth_mm
geometric object points, smoothed lines
scale linear
statistical transform none
coordinate system rectangular
faceting none
ggplot(FILL_THIS_IN) +
  aes(FILL_THIS_IN, FILL_THIS_IN)
  FILL_THIS_IN() + 
  geom_smooth()

You can control aesthetics for individual layers by adding an aes() inside the layer function, like this:

geom_point(aes(color = COLOR_VARIABLE))

Modify your code above so that the points (but not the smooth line) have their color mapped to species:

ggplot(FILL_THIS_IN) +
  aes(FILL_THIS_IN, FILL_THIS_IN)
  FILL_THIS_IN() + 
  geom_smooth()

Now, instead, map color in the global aes() call for the plot. What happens?

ggplot(FILL_THIS_IN) +
  aes(FILL_THIS_IN, FILL_THIS_IN)
  FILL_THIS_IN() + 
  geom_smooth()

Things to keep in mind:

  • Aesthetics mapped outside of a specific layer apply globally
  • Aesthetics mapped inside a geom layer apply only to that layer.
  • If the same aesthetic appears both globally and in a layer, the layer-specific one wins

15.3 Assigning a ggplot2 object and adding to it

You can store the output of the plot in a variable. Assign the mauan plot above to a variable named p, then add a layer to p that adds a dark green smoothed line to the plot.

FILL_THIS_IN

p +
  FILL_THIS_IN()

15.4 Fix Me!

What’s wrong with the following code? Fix it.

ggplot(gapminder) +
  geom_point(x = gdpPercap, y = lifeExp, alpha = 0.1)

What’s wrong with this code? Fix it.

ggplot(cars) +
  geom_point(aes(x = speed, y = dist, color = "blue"))