01 / 21

Building ggplots

Master the grammar of graphics in R: connect data to visual aesthetics and layer on geometric objects to create publication-quality plots.

Data Science R Programming

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

1. Data
A data frame (or tibble) containing the variables you want to visualize. Passed as the first argument to ggplot().
2. Aesthetics
Mappings defined inside aes() that connect columns in your data to visual properties: x-position, y-position, color, size, shape.
3. Geoms
Geometric objects like geom_point(), geom_line(), or geom_bar() that determine what shapes appear on the plot.

How Layers Stack Up

ggplot(data, aes(...)) + geom_point() + labs() / theme() Final Plot + + = Foundation Geometry Customization

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

R
ggplot(data = my_data, aes(x = var1, y = var2)) +
  geom_point()
1
ggplot() initializes the plot and sets the data frame.
2
aes() maps columns to visual channels: x, y, color, size, shape.
3
geom_*() tells R what shape to draw: points, lines, bars, etc.

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.

x and y
Position on the horizontal and vertical axes. Almost every plot needs these.
color
Maps a variable to the color of points, lines, or outlines. Groups data visually.
size
Maps a variable to the area of points. Useful for showing a third numeric dimension.

Inside vs. Outside aes()

R
# 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

geom_point()
Scatter plots. Shows individual observations as dots. Best for exploring relationships between two numeric variables.
geom_line()
Line charts. Connects observations in order. Ideal for time series and trends.
geom_bar()
Bar charts. Counts occurrences by default. Use geom_col() if you already have the heights.
geom_histogram()
Histograms. Shows the distribution of a single numeric variable by binning values.

Building a Plot: Step by Step

1
Identify your data. Which data frame are you working with? What are the column names?
2
Choose your aesthetics. Which variable goes on x? On y? Should color or size represent a third variable?
3
Pick a geom. What shape best tells the story? Points for relationships, bars for counts, lines for trends.
4
Write the code. Start with ggplot(data, aes(...)), then add + geom_*().
5
Refine. Add labels with labs(), adjust the theme, tweak colors if needed.

Example 1: Basic Scatter Plot

Plot engine displacement (displ) vs. highway mileage (hwy) from the built-in mpg dataset.

R
ggplot(data = mpg, aes(x = displ, y = hwy)) +
  geom_point()
2 3 4 5 15 25 35 45 displ hwy

Example 2: Adding Color

Map the class variable to color to see how vehicle type affects the relationship.

R
ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
  geom_point()
2 3 4 5 15 25 35 45 compact midsize suv pickup subcompact

Example 3: Bar Chart with geom_bar()

Count how many cars are in each class using geom_bar(), which automatically computes counts.

R
ggplot(mpg, aes(x = class)) +
  geom_bar(fill = "#818cf8")
0 30 60 2seater compact midsize minivan pickup subcomp suv 5 47 41 11 33 35 62

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()

R
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()
labs()
Sets title, subtitle, axis labels, and legend titles. Always label your axes clearly.
theme()
Controls non-data elements: font sizes, grid lines, background color, legend position. Built-in themes like theme_minimal() give instant polish.

Common Mistakes

✕ Forgetting the +
Each layer must be connected with +. Starting a new line without + ends the plot early.
✕ aes() Placement
Putting color = "blue" inside aes() creates a legend with one blue level. Move fixed values outside aes().
✕ Wrong Geom
Using geom_bar() when data is pre-summarized gives wrong counts. Use geom_col() or set stat = "identity".
✕ Quoting Variables
Inside aes(), variable names go unquoted: aes(x = displ), not aes(x = "displ").

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?