Visualizing grain yields

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

The corn dataset

glimpse(corn)
Observations: 6,381
Variables: 6
$ year                   <int> 1866, 1866, 1866, 1866, 1866, 1866...
$ state                  <chr> "Alabama", "Arkansas", "California...
$ farmed_area_acres      <dbl> 1050000, 280000, 42000, 57000, 200...
$ yield_bushels_per_acre <dbl> 9.0, 18.0, 28.0, 34.0, 23.0, 9.0, ...
$ farmed_area_ha         <dbl> 424919.92, 113311.98, 16996.80, 23...
$ yield_kg_per_ha        <dbl> 79.29892, 158.59784, 246.70776, 29...
Introduction to Writing Functions in R

ggplot2: drawing multiple lines

ggplot(dataset, aes(x, y)) +
  geom_line(aes(group = group))

A line plot with multiple lines on it. The data is made up and not very exciting, but the point is that the lines are grouped by the group column in the data frame.

Introduction to Writing Functions in R

ggplot2: smooth trends

ggplot(dataset, aes(x, y)) +
  geom_line(aes(group = group)) +
  geom_smooth()

It's the same line plot from the previous slide, but now there is an extra line with a smooth trend on it. That line isn't grouped because the grouped aesthetic was part of the line geom, not the whole plot. Clever, right?

Introduction to Writing Functions in R

ggplot2: facetting

ggplot(dataset, aes(x, y)) +
  geom_line(aes(group = group)) +
  geom_smooth() +
  facet_wrap(vars(facet))

It's the same plot as last time, but now there are four panels labelled 'A' to 'D', because of the call to facet_wrap.

Introduction to Writing Functions in R

USA Census regions

It's a statebin plot, which means that each US state is represented as a square, and the squares are laid out in rows and columns that are arranged a little bit like the shape of the USA. Each census region has a different color of squares.

Introduction to Writing Functions in R

dplyr inner joins

dataset1 %>%
  inner_join(dataset2, by = "column_to_join_on")
Introduction to Writing Functions in R

Let's practice!

Introduction to Writing Functions in R

Preparing Video For Download...