ggplot(mpg) +
geom_bar(aes(x = class))One Categorical Variable
With a bar chart, you visualize how often each category of a categorical variable occurs.
Bar charts
Do: run the code below, which visualizes the drv variable (drive train: front-, rear-, or four-wheel drive).
See: a bar for each level of drv, with height of that bar equal to the number of cars in the dataset with that drive train.
Predict: geom_bar() was given only an x mapping, no y. What do you think y is set to by default?
Explain: geom_bar() automatically counts the rows for each level of the x variable and maps that count to the y-axis. You never have to compute the counts yourself; stat_count() (the statistical transformation behind geom_bar()) does it for you.
Predict what the bar chart will look like if you map x = class instead of x = drv. How many bars do you expect, and which one do you expect to be tallest? Then run the code to check.
class has more distinct levels than drv (e.g., “compact”, “midsize”, “suv”, …). Run levels(factor(mpg$class)) if you want to check how many there are before plotting.
There are seven vehicle classes in mpg, so you get seven bars. “suv” and “compact” turn out to be the two most common classes in this dataset.
Fill vs colour
Do: run this, using colour to map class.
See: each bar has a coloured outline matching its class, but the inside of every bar is still grey.
Predict: each bar is already a different class, so mapping colour = class doesn’t add new information, but it does show you something about how bars are drawn. Before running the next chunk, predict: if you use fill = class instead of colour = class, what part of the bar do you expect to change?
Explain: now each bar is solid, filled with a colour matching its class, and the outline is no longer distinct from the fill. Bars (and other shapes with an interior, like boxplots or areas) have two separate colour aesthetics: colour sets the outline, and fill sets the interior. With colour = class the bars stayed grey inside with coloured borders; with fill = class the bars became solid colour. Points have no interior to fill, so colour is the only relevant aesthetic for them.