Bar & Distribution Charts
It is Saturday and Maya the bakery owner has logged every order, 30 of them, into a little table: the headline item the customer came for, what they spent, and whether it was the morning rush or a quiet afternoon. Two questions are nagging her. Which pastry is pulling its weight? and what does a typical order actually look like? A scatter or a line, the charts from Lesson 2, answer neither. These questions need bars and distributions.
In Lesson 2 you used geom_point() for a relationship and geom_line() for a value moving through time. Now you meet the charts that compare categories and reveal the shape of a single column of numbers.
By the end of this lesson you will be able to:
- Use
geom_col()to compare an amount across categories, andgeom_bar()to compare counts, and say exactly which one does the counting - Draw a histogram with
geom_histogram()to see how one continuous variable is spread, and choose a sensible bin width - Read and draw a boxplot with
geom_boxplot()to compare a distribution across groups - Match a question to the chart that answers it
Prerequisites: Lesson 1, the grammar of graphics (data, aes(), geoms, layering with +) and Lesson 2, scatter and line charts. Every new term is defined as it appears.
Bars compare categories
A bar chart answers one question: how do categories compare on some number? Each category gets its own bar, and the bar's height is the number. Maya's pastries are the categories; the dollars each one earned is the number.
Start, as always, by building Maya's Saturday right here. Each lesson runs in a fresh R session, so the data lives on this page (run this once):
Maya already knows her per-pastry revenue is worth plotting, so first she totals it up, one row per pastry, with the dplyr verbs from earlier in the course:
Now revenue is an amount she already has, one value per category. The geom that draws a bar at a height you supply is geom_col() ("col" for column): map pastry to x and revenue to y, and it does no arithmetic, it just draws your numbers.
The bars rank the pastries by money. Sourdough wins, on only 3 orders, while Coffee, ordered far more often, comes second. Hold on to that surprise.