The Grammar of Graphics
Maya runs a small neighbourhood bakery, and by now she can wrangle her till data and summarise it: last week she pulled seven rows, one per day, each with the foot traffic (people who walked in) and the revenue (dollars taken). But a column of seven numbers does not show her what is going on. The moment she draws it, the story jumps out: busier days take more money, and Saturday towers over the rest.
That picture below is a ggplot. By the end of this lesson you will understand the small set of rules, the grammar, that builds it, and every other chart in this course.
By the end you will be able to:
- Name the three core parts of every ggplot: the data, the aesthetic mappings, and the geoms
- Build a plot in R by stacking
ggplot(data)+aes()+ a geom, one layer at a time with+ - Read ggplot code as a sentence, and swap one word to get a different chart
Prerequisites: you can run R and load a package with library(), and you have a data frame in hand (you built one in the dplyr and EDA sections). Every plotting term is defined as it appears.
Why "grammar"?
English has a handful of grammar rules, a subject, a verb, an object, and from them you build endless different sentences. The grammar of graphics is the same idea for charts: a small set of parts that combine to describe almost any plot you can imagine. ggplot2 is R's implementation of it, which is why a scatterplot, a line chart and a bar chart all read almost the same in code.
Three parts do most of the work, and you assemble them in layers, stacked one on top of the next with a +:
- Data - the data frame you want to picture (Maya's week).
- Aesthetic mappings - rules that connect a column to a visual channel: which column goes on the x axis, which on the y axis, which controls colour.
- Geoms - the geometric objects that actually draw the data: points, lines, bars.
Hold those three in mind; the rest of the lesson adds them one at a time.