Elevating Your Visualizations (ggplot2 Customization)
7 min read
Welcome back, data artist! 🎨
By now, you likely know how to map x to a column and y to another to create a scatter plot. That’s great! But let’s be honest—default ggplot2 plots, while functional, often look like they were dressed by a chaotic algorithm.
In the professional world, a chart isn't just about showing data; it's about communication. If your stakeholder has to squint to read the axis or guess what the blue dot means, you've lost them.
In this module, we are moving from "I made a chart" to "I crafted a data narrative." We will tackle the "Spaghetti Plot" problem, fix ugly colors, label things properly so your future self doesn't get confused, and style your plots for publication.
Let's load our toolkit. We will use the built-in mpg dataset (fuel economy data from 1999 to 2008 for 38 popular models of cars) because it’s messy enough to require customization.
library(tidyverse)
# Peek at the data
glimpse(mpg)1. Faceting: Creating Small Multiples 🪟
The Problem: Overplotting (The "Fruit Salad" Effect)
Imagine you want to compare highway mileage (hwy) vs. engine displacement (displ) for every class of car. If you plot them all on one graph using color, you often get a jumbled mess where points overlap, and it’s impossible to see trends for specific groups.
The Solution: Faceting
Faceting splits one plot into multiple smaller plots (panels) based on a categorical variable. Edward Tufte, the grandfather of data viz, calls these "Small Multiples." They allow your brain to compare patterns without being overwhelmed by noise.
facet_wrap()
Use this when you have one variable to split by. It wraps the panels into a rectangular layout.
Syntax: facet_wrap(~ variable_name)
Note: The tilde ~ is R's way of saying "by" or "dependent on".
# The Problem: Too much overlapping
ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
geom_point()
# The Solution: Give every class its own room
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_wrap(~ class, nrow = 2) # Force 2 rows layoutfacet_grid()
Use this when you have two variables and want a matrix (grid) layout.
Syntax: facet_grid(row_variable ~ column_variable)
# Compare drive train (drvm: f=front, r=rear, 4=4wd) vs Number of cylinders
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_grid(drv ~ cyl)🧪 Industry Tip: If your facets have vastly different ranges of data (e.g., one group ranges from 0-10 and another 0-1000), the default fixed scales will make the small data look like a flat line. Use scales = "free" inside the function to let each panel have its own axis limits.
facet_wrap(~ class, scales = "free_y") # Y-axis adjusts for each plot independently2. Scales and Coordinates: Controlling Axes, Limits, and Colors 📏
The Problem: Misleading or Ugly Defaults
Defaults are safe, but rarely optimal.
- Axis limits: Maybe you want to focus on a specific region, or start the Y-axis at 0 (mandatory for bar charts!).
- Colors: The default rainbow/hue palette is not colorblind-friendly and prints poorly in black and white.
The Solution: scale_* functions
The grammar of graphics uses "scales" to control how data values map to visual properties.
Controlling Axes (scale_x_continuous, scale_y_continuous)
You can force breaks (tick marks), change labels (add $ or %), or set limits.
ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
geom_point() +
scale_x_continuous(
name = "Engine Displacement (Liters)",
breaks = seq(2, 7, by = 1), # Ticks at 2, 3, 4...
limits = c(1, 8) # Show range 1 to 8
)Controlling Colors (scale_color_*, scale_fill_*)
Industry Standard: Use the Viridis palette. It is scientifically designed to be perfectly perceptually uniform, works in black and white, and is colorblind accessible. Plus, it looks cool.
ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
geom_point(size = 3) +
scale_color_viridis_d() # _d for discrete data, _c for continuousCoordinates (coord_flip, coord_cartesian)
coord_flip(): Swaps x and y. Essential for bar charts with long category names.coord_cartesian(): Zooms into the plot without throwing away data.
⚠️ Warning: If you use scale_y_continuous(limits = c(0, 20)), ggplot actually deletes data points outside that range before calculating statistics (like trend lines). If you just want to zoom in, use coord_cartesian(ylim = c(0, 20)).
# Boxplot of hwy mileage by class
ggplot(mpg, aes(x = class, y = hwy)) +
geom_boxplot() +
coord_flip() # Now readable without cricking your neck!3. Labels and Annotations: Titles, Subtitles, and Captions 🏷️
The Problem: "Mystery Charts"
You create a plot and email it to your boss. Five minutes later, they reply: "What is this? What are the units? Is this bad or good?"
The Solution: labs()
Always label your axes, give a title, and cite your source.
ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
geom_point() +
labs(
title = "Fuel Efficiency vs. Engine Size",
subtitle = "Larger engines generally have lower highway mileage",
x = "Engine Displacement (Liters)",
y = "Highway MPG",
color = "Car Class",
caption = "Source: EPA Fuel Economy Data (1999-2008)"
)The Solution: annotate()
Sometimes you need to point to a specific outlier and say "Look at this!".
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
annotate(
geom = "text",
x = 6, y = 40,
label = "Outliers here!",
color = "red",
fontface = "bold"
) +
annotate(
geom = "rect",
xmin = 5.5, xmax = 7, ymin = 10, ymax = 45,
alpha = 0.2, fill = "red"
)4. Themes: Changing the Overall Look and Feel 🎩
The Problem: The "Gray Background" Fatigue
The default ggplot background (gray with white gridlines) is iconic but often too heavy for presentations or printed reports. It uses a lot of ink.
The Solution: Built-in Themes
ggplot2 comes with complete skins.
theme_gray(): The default.theme_minimal(): Minimalist, no background. (Highly recommended)theme_classic(): Looks like base R / Excel (axis lines only).theme_void(): Empty (great for maps).
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
theme_minimal()Advanced: theme() customization
This is where you tweak the "non-data ink." A frequent frustration in data science is long text labels overlapping on the x-axis.
Solution: Rotate the text.
ggplot(mpg, aes(x = manufacturer, y = hwy)) +
geom_boxplot() +
theme_minimal() +
theme(
# Rotate x-axis text 45 degrees and align it to the right
axis.text.x = element_text(angle = 45, hjust = 1),
# Make the title big and bold
plot.title = element_text(size = 14, face = "bold"),
# Move legend to the bottom
legend.position = "bottom"
)Fun Fact: There is a package called ggthemes that lets you make your plots look like they were made in Excel 97, The Economist, or even using the colors from a Wes Anderson movie. 🎬
🧱 Putting it all together (The "Pro" Plot)
Let's combine everything we've learned into one polished visualization.
ggplot(mpg, aes(x = displ, y = hwy, color = drv)) +
geom_point(alpha = 0.7) +
facet_wrap(~ year) + # Split by year to see temporal changes
scale_color_viridis_d(name = "Drive Train", labels = c("4WD", "Front", "Rear")) +
scale_x_continuous(name = "Engine Size (L)", breaks = seq(2, 7, 1)) +
scale_y_continuous(name = "Highway MPG") +
labs(
title = "Car Efficiency: 1999 vs 2008",
subtitle = "Engine size remains the dominant factor in fuel economy",
caption = "Data: EPA"
) +
theme_minimal() +
theme(legend.position = "top")Congratulations! You have graduated from making "charts" to designing "graphics." Go forth and visualize! 🚀
📚 References & Further Reading
- Official Documentation: ggplot2.tidyverse.org
- R Graphics Cookbook: Detailed Recipes for Customization
- Viridis Palette: Introduction to Colorblind Friendliness
- The Cheat Sheet: Data Visualization with ggplot2 Cheat Sheet
Challenge
You are tasked with creating a publication-ready data visualization using the mpg dataset in R with the ggplot2 package. Starting with the provided basic scatter plot, you must add several layers of customization to enhance its clarity and aesthetic appeal.
Your goal is to modify the initial code to produce a single complex plot that meets all of the following requirements:
- The plot should display highway miles per gallon (
hwy) on the y-axis versus engine displacement (displ) on the x-axis. - The color of the points must be mapped to the vehicle
class. - Create small multiples, or facets, for each
manufacturer. The facets should wrap into a grid automatically. - Allow the y-axis scales to be independent for each facet to accurately represent the data range within each manufacturer's plot.
- Apply the discrete version of the "Viridis" color palette to the points.
- Use the
labs()function to add the following labels:- Title: "Engine Displacement vs. Highway MPG by Manufacturer"
- Subtitle: "An analysis of vehicle efficiency across classes"
- X-axis label: "Engine Displacement (Liters)"
- Y-axis label: "Highway Miles Per Gallon (MPG)"
- Legend Title: "Vehicle Class"
- Caption: "Source: ggplot2 mpg dataset"
- Add a text annotation directly onto the plot canvas at the coordinates
x = 6,y = 40with the text "High Efficiency Region". - Switch the overall plot theme to
theme_minimal(). - Further refine the theme by moving the entire legend to the
bottomof the plot.
Expected result
The final output should be a single ggplot2 visualization. This visualization will be a multi-panel grid of scatter plots, where each panel corresponds to a different car manufacturer.
The key features of the correct plot are:
- Faceting: The plot is faceted by
manufacturerusingfacet_wrap(). - Independent Scales: Each facet has its own y-axis scale (
scales = "free_y"). - Aesthetics: A scatter plot of
displvs.hwywith points colored byclass. - Color Palette: The colors used for the points must come from the discrete Viridis scale.
- Labels: The plot must have a specific title, subtitle, caption, and custom labels for the x-axis, y-axis, and legend as detailed in the instructions.
- Theme: The plot must use
theme_minimal()as a base, with the legend explicitly positioned at the bottom. - Annotation: A text label reading "High Efficiency Region" must be present in the plot area near the specified coordinates.