Lesson 2 of 4

Scatter & Line Charts

Maya the bakery owner has a new question. Through one warm fortnight she wrote down, for each of 14 days, the daily high temperature and the number of iced coffees she sold. She suspects hot days sell more iced coffee, but a column of numbers will not tell her. The moment she plots temperature against sales, the answer leans off the page.

In Lesson 1 you learned the grammar: data, an aesthetic mapping inside aes(), and a geom added with +. Now you put it to work with the two geoms you will reach for most.

By the end of this lesson you will be able to:

  • Choose geom_point (a scatter) or geom_line for a given question, and say why
  • Map a third variable to colour and to size to pack more into one chart
  • Add a trend line with geom_smooth() that summarises the whole cloud in one stroke

Prerequisites: Lesson 1, the grammar of graphics (data, aes() mappings, geoms, layering with +). Every new term is defined as it appears.

The workhorse

The scatter: one point per row

A scatterplot answers one precise question: how do two continuous measurements move together? You map one to x, the other to y, and geom_point() draws exactly one dot per row at its (x, y) spot. Fourteen days become fourteen dots, and the shape of the cloud is the relationship.

Each lesson runs in a fresh R session, so build Maya's fortnight right here (run this once):

RInteractive R
library(ggplot2) maya <- data.frame( day = c("Mon","Tue","Wed","Thu","Fri","Sat","Sun", "Mon","Tue","Wed","Thu","Fri","Sat","Sun"), day_num = 1:14, temp_c = c(19,22,20,24,26,25,23,28,30,27,31,29,33,30), # daily high, Celsius iced_coffees = c(45,52,44,66,78,92,82,96,112,90,120,104,145,126), day_type = c("weekday","weekday","weekday","weekday","weekday","weekend","weekend", "weekday","weekday","weekday","weekday","weekday","weekend","weekend"), foot_traffic = c(120,132,118,150,168,230,210,175,190,165,198,180,250,224) ) head(maya)

  

Now the scatter is the grammar from Lesson 1 with geom_point() as the geom:

RInteractive R
ggplot(maya, aes(x = temp_c, y = iced_coffees)) + geom_point(size = 3, colour = "steelblue")

  

The dots climb from lower-left to upper-right: hotter days sold more iced coffee. The widget below reports Pearson's r, a single number from \(-1\) to \(+1\) that measures how tightly the dots hug a straight line (you will study r in depth in correlation analysis; here it just confirms what your eye sees).