Building ggplots
Master the grammar of graphics in R: connect data to visual aesthetics and layer on geometric objects to create publication-quality plots.
What is ggplot2?
ggplot2 is an R package for creating data visualizations. Instead of memorizing separate commands for each chart type, you build plots by combining layers using a consistent grammar.
Every ggplot starts with the same function call: ggplot(). From there, you add pieces with the + operator, stacking layers like building blocks.
Three Essential Ingredients
How Layers Stack Up
You build a ggplot by adding layers with the + operator. The base layer sets data and aesthetics. Each additional layer adds geometry, labels, or theme adjustments. Order matters: later layers draw on top.
The Core Template
ggplot(data = my_data, aes(x = var1, y = var2)) + geom_point()
Understanding aes()
aes() stands for aesthetic mapping. It tells ggplot which columns in your data control which visual properties. The key insight: aes() maps data to visuals, it does not set fixed values.
Inside vs. Outside aes()
# Color MAPPED to a variable (inside aes) ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point() # Color SET to a fixed value (outside aes) ggplot(mpg, aes(x = displ, y = hwy)) + geom_point(color = "blue")
| Inside aes() | Outside aes() | |
|---|---|---|
| Purpose | Map a variable to a visual | Set a fixed value |
| Legend? | ✓ Auto-generated | ✕ No legend |
| Example | color = class | color = "blue" |
| Quotes? | ✕ No quotes | ✓ Needs quotes |
Common Geoms
Building a Plot: Step by Step
Example 1: Basic Scatter Plot
Plot engine displacement (displ) vs. highway mileage (hwy) from the built-in mpg dataset.
ggplot(data = mpg, aes(x = displ, y = hwy)) + geom_point()
Example 2: Adding Color
Map the class variable to color to see how vehicle type affects the relationship.
ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point()
Example 3: Bar Chart with geom_bar()
Count how many cars are in each class using geom_bar(), which automatically computes counts.
ggplot(mpg, aes(x = class)) + geom_bar(fill = "#818cf8")
geom_bar() vs. geom_col()
Both produce bar charts, but they handle the y-axis differently. This is one of the most commonly confused pairs in ggplot2.
| geom_bar() | geom_col() | |
|---|---|---|
| Y-axis | Counts rows automatically | Uses a y variable you provide |
| Required aes() | x only | x and y |
| Default stat | stat = "count" | stat = "identity" |
| Use when | Raw data: count categories | Pre-summarized data |
Polishing with labs() and theme()
ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point() + labs( title = "Engine Size vs. Fuel Efficiency", x = "Displacement (liters)", y = "Highway MPG", color = "Vehicle Class" ) + theme_minimal()
Common Mistakes
Quick Reference Table
| Component | Syntax | Purpose |
|---|---|---|
| Initialize | ggplot(data, aes(...)) | Set data and mappings |
| Scatter | + geom_point() | Plot individual points |
| Line | + geom_line() | Connect points in order |
| Count bars | + geom_bar() | Count and plot categories |
| Value bars | + geom_col() | Plot pre-computed heights |
| Histogram | + geom_histogram() | Distribution of one variable |
| Labels | + labs(title, x, y) | Add titles and axis labels |
| Theme | + theme_minimal() | Change overall look |
Question 1 of 5
Which function initializes a ggplot and sets the data frame?
Question 2 of 5
You want every point on your scatter plot to be red. Where should you put color = "red"?
Question 3 of 5
What does the + operator do in a ggplot call?
Question 4 of 5
You have a data frame sales with columns product and revenue. You want a bar chart where each bar's height equals the revenue value. Which geom should you use?
Question 5 of 5
Which code correctly creates a scatter plot of height vs. weight from a data frame called students, with points colored by grade?