Learn tidyverse · 7/13

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.

  1. Data: The tibble or data.frame containing your information.
  2. Aesthetics (aes): The "mapping" layer. This tells ggplot which columns in your data correspond to visual properties (x-axis, y-axis, color, size, shape).
  3. Geometries (geom): The actual ink on the page. Are we drawing points? Bars? Lines?

The Syntax Skeleton:

r
ggplot(data = <YOUR_DATA>) +
  <GEOM_FUNCTION>(mapping = aes(<YOUR_MAPPINGS>))

Industry Fact: ggplot2 implements 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.

r
# If you haven't installed it yet:
# install.packages("tidyverse")

library(tidyverse)

Let's build a canvas.

r
# 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.

r
# 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.

r
# 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).

r
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
  geom_point(color = "blue") +
  geom_smooth(method = "lm", color = "red")

Key Takeaways:

  1. Global vs. Local Aes: We defined aes(x = displ, y = hwy) in the main ggplot() function. This means both the points and the line inherit these X and Y coordinates.
  2. Fixed Attributes: Notice color = "blue" is outside the aes() function inside geom_point.
    • Inside aes(): "Map color to a variable" (e.g., color based on car class).
    • Outside aes(): "Make everything this specific color."
  3. geom_smooth: We used method = "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_smooth is 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

  1. geom_bar(): The default. It counts the number of rows for each category automatically.
  2. 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?

r
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?

r
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
  geom_boxplot() +
  coord_flip() # Pro Tip: Flips X and Y axes for easier reading of labels

Visualizing 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.

r
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 with binwidth.

Hands-on Practice: Density Plot

If you want a smoother look (great for presentations):

r
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

  1. Initialize: ggplot(data = df)
  2. Map: aes(x = col_A, y = col_B, color = col_C)
  3. Draw: + geom_point() / geom_bar() / geom_boxplot()
  4. Refine: Add layers, change colors, adjust labels.

📚 References & Further Reading

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:

  1. Load the ggplot2 library to make the mpg dataset available.
  2. Create a plot with engine displacement (displ) on the x-axis and highway miles per gallon (hwy) on the y-axis.
  3. Generate a scatter plot where the color of each point is determined by the vehicle's class.
  4. In the same scatter plot, the size of each point should be mapped to the number of cylinders (cyl).
  5. Overlay a single, black linear regression trend line (geom_smooth with method = "lm") that represents the overall trend for all data points combined, not for each individual class.
  6. The trend line must be rendered without its standard error confidence interval ribbon.

Expected result

The solution must be a single ggplot expression.

  1. The code must start by calling ggplot() with data = mpg. The global aesthetic mapping aes(x = displ, y = hwy) should be set within this initial call.
  2. A geom_point() layer must be added. This layer's aesthetic mapping, aes(color = class, size = cyl), must be defined locally inside this geom_point() call.
  3. A geom_smooth() layer must be added. This layer must specify method = "lm". To make the line black, the attribute color = "black" must be set outside of any aes() mapping. To hide the confidence interval, the argument se = FALSE must be included.
R

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.