The Grammar of Graphics: Introduction to ggplot2
7 min read
Welcome to the visual arts department of Data Science! 🎨
If you have ever tried to make a complex chart in Excel, you probably spent 3 hours clicking through menus, only to realize you selected the wrong data range, and now the "Undo" button is greyed out. We have all been there. It is a shared trauma.
In the tidyverse, we don't click buttons. We build plots using a coherent system known as the Grammar of Graphics.
This guide covers ggplot2, the industry-standard package for data visualization in R. It is powerful, flexible, and once you click with its logic, you will never want to look at a spreadsheet chart again.
🧱 1. The Anatomy of a Plot: Data, Aesthetics (aes), and Geometries (geom)
Definition
ggplot2 is based on the idea that you can build any plot from the same few components: a data set, a set of aesthetic mappings (how data maps to color, size, or position), and geometric objects (points, lines, bars) to represent those aesthetic mappings.
The Problem
In many tools (like base R plotting or simple charting software), a "Scatterplot" and a "Line Chart" are treated as completely different animals. You have to memorize a different function for every single type of chart. If you want to change a dot to a bar, you have to start over.
The Solution
ggplot2 decouples the data from the visual representation. You tell R: "Here is my data, here are the variables I care about, now draw them using this shape."
The 3 Core Layers
To build a graph, we stack layers.
- Data: The
tibbleordata.framecontaining your information. - Aesthetics (
aes): The "mapping" layer. This tellsggplotwhich columns in your data correspond to visual properties (x-axis, y-axis, color, size, shape). - Geometries (
geom): The actual ink on the page. Are we drawing points? Bars? Lines?
The Syntax Skeleton:
ggplot(data = <YOUR_DATA>) +
<GEOM_FUNCTION>(mapping = aes(<YOUR_MAPPINGS>))Industry Fact:
ggplot2implements the concepts from Leland Wilkinson's book The Grammar of Graphics (1999). It is literally a grammar—syntax and rules—for communicating data.
Hands-on Example
We will use the mpg dataset (included in tidyverse), which contains fuel economy data for popular cars.
Setup:
First, ensure you have the tidyverse loaded.
# If you haven't installed it yet:
# install.packages("tidyverse")
library(tidyverse)Let's build a canvas.
# Step 1: The Canvas
ggplot(data = mpg)
# Result: A grey empty box. Why? We haven't told it what to draw yet.Now, let's map the axes.
# Step 2: The Aesthetics
ggplot(data = mpg, mapping = aes(x = displ, y = hwy))
# Result: A grey box with X and Y axes labeled and scaled.
# 'displ' is engine size, 'hwy' is highway miles per gallon.Finally, let's add the ink.
# Step 3: The Geometry
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point()What just happened?
We told R: "Take the mpg data. Map engine size to X and mileage to Y. Represent each row as a point."
📈 2. Essential Geoms: Scatterplots and Trend Lines
Definition
- Scatterplot (
geom_point): Visualizes the relationship between two continuous variables. - Trend Line (
geom_smooth): A statistical line that summarizes the pattern of the data.
The Problem
Raw data is noisy. If you plot 1,000 points, it looks like a swarm of bees. It is difficult to see if the general trend is going up, down, or curving.
The Solution
We layer a smoothing geometry on top of the point geometry. Because ggplot2 is additive (using the + sign), we can stack these visuals easily.
Hands-on Practice
Let's see if bigger engines (displ) actually consume more fuel (hwy).
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(color = "blue") +
geom_smooth(method = "lm", color = "red")Key Takeaways:
- Global vs. Local Aes: We defined
aes(x = displ, y = hwy)in the mainggplot()function. This means both the points and the line inherit these X and Y coordinates. - Fixed Attributes: Notice
color = "blue"is outside theaes()function insidegeom_point.- Inside
aes(): "Map color to a variable" (e.g., color based on car class). - Outside
aes(): "Make everything this specific color."
- Inside
geom_smooth: We usedmethod = "lm"(Linear Model) to draw a straight regression line. By default, it uses "loess" (a curvy line that hugs the data).
Funny Imagination: If your scatterplot looks like a Rorschach test,
geom_smoothis the therapist telling you what it actually means.
📊 3. Categorical Geoms: Bar Charts and Boxplots
Definition
- Bar Chart (
geom_bar): Used for comparing quantities across categorical groups. - Boxplot (
geom_boxplot): Visualizes the distribution, median, and outliers of a continuous variable split by categories.
The Problem with Bars
A common point of confusion in the industry is the difference between counting rows and plotting values that already exist.
- Scenario A: You have a list of 1000 car sales. You want a bar chart showing how many were SUVs. (R needs to count them).
- Scenario B: You have a table saying "SUV: 500". (R just needs to draw a bar to height 500).
The Solution: geom_bar vs geom_col
geom_bar(): The default. It counts the number of rows for each category automatically.geom_col(): Use this if your data already has the totals calculated.
Hands-on Practice: Bar Charts
Which class of car is most common in our dataset?
ggplot(data = mpg, mapping = aes(x = class)) +
geom_bar()Note: We did not provide a y aesthetic. geom_bar creates a new variable called count under the hood.
The Problem with Averages
Averages hide secrets. If Bill Gates walks into a dive bar, the "average" wealth of everyone in the bar becomes a billion dollars. This is misleading.
The Solution: Boxplots
Boxplots show the Median (the middle person), the Interquartile Range (where 50% of the data lives), and the Outliers (the billionaires in the dive bar).
Hands-on Practice: Boxplots
Do SUVs have a wider range of mileage than compact cars?
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot() +
coord_flip() # Pro Tip: Flips X and Y axes for easier reading of labelsVisualizing the Boxplot:
- Thick middle line: Median.
- The Box: The middle 50% of cars.
- The Whiskers: The expected range.
- The Dots: Outliers (cars that perform weirdly better or worse than expected).
🏔️ 4. Histograms and Density Plots: Visualizing Distributions
Definition
These plots show how a single continuous variable is distributed. Is the data clustered around 50? Is it "Normal" (bell-shaped)? Is it skewed?
The Problem
You have 10,000 data points of customer ages. A scatterplot would just look like a solid black line. You need to "bin" the data—group ages 10-20, 20-30, etc.—to see the shape.
The Solution
geom_histogram(): Chops data into bins and counts items in each bin.geom_density(): A smooth, continuous version of a histogram (essentially a histogram with infinite bins).
Hands-on Practice: Histogram
Let's look at the distribution of highway mileage (hwy) for all cars.
ggplot(data = mpg, mapping = aes(x = hwy)) +
geom_histogram(binwidth = 2, fill = "steelblue", color = "white")Warning: When you run this, R might yell at you:
stat_bin() using bins = 30. Pick better value with binwidth.
Do not ignore this. The shape of a histogram can change drastically depending on how wide your bins are. Always experiment withbinwidth.
Hands-on Practice: Density Plot
If you want a smoother look (great for presentations):
ggplot(data = mpg, mapping = aes(x = hwy)) +
geom_density(fill = "orange", alpha = 0.5)Why alpha?alpha controls transparency (0 to 1). If you overlay multiple density plots (e.g., comparing mileage of 1999 cars vs 2008 cars), transparency allows you to see the overlap.
📝 Summary Checklist
- Initialize:
ggplot(data = df) - Map:
aes(x = col_A, y = col_B, color = col_C) - Draw:
+ geom_point()/geom_bar()/geom_boxplot() - Refine: Add layers, change colors, adjust labels.
📚 References & Further Reading
- Official ggplot2 Documentation - The source of truth.
- RStudio Data Visualization Cheat Sheet - Print this and tape it to your wall.
- R for Data Science (2e): Data Visualization - The best book for learning Tidyverse.
Challenge
Challenge: Multi-Layered MPG Data Visualization
Your task is to create a complex, multi-layered data visualization using the built-in mpg dataset from the ggplot2 library. You will investigate the relationship between engine displacement and highway fuel efficiency, while simultaneously encoding additional vehicle characteristics.
Requirements:
- Load the
ggplot2library to make thempgdataset available. - Create a plot with engine displacement (
displ) on the x-axis and highway miles per gallon (hwy) on the y-axis. - Generate a scatter plot where the color of each point is determined by the vehicle's
class. - In the same scatter plot, the size of each point should be mapped to the number of cylinders (
cyl). - Overlay a single, black linear regression trend line (
geom_smoothwithmethod = "lm") that represents the overall trend for all data points combined, not for each individual class. - The trend line must be rendered without its standard error confidence interval ribbon.
Expected result
The solution must be a single ggplot expression.
- The code must start by calling
ggplot()withdata = mpg. The global aesthetic mappingaes(x = displ, y = hwy)should be set within this initial call. - A
geom_point()layer must be added. This layer's aesthetic mapping,aes(color = class, size = cyl), must be defined locally inside thisgeom_point()call. - A
geom_smooth()layer must be added. This layer must specifymethod = "lm". To make the line black, the attributecolor = "black"must be set outside of anyaes()mapping. To hide the confidence interval, the argumentse = FALSEmust be included.