Introduction to ggplot2

The grammar of graphics, color, and themes

Today’s roadmap

  • Grammar of graphics: the mental model behind every ggplot
  • Aesthetics and geoms: mapping data to visual properties
  • Facets, labels, scales: comparisons and readability
  • Color: theory, hex codes, palettes, accessibility
  • Themes: built-in, theme(), your own reusable theme
  • Layout and export: combining plots, sizing, saving
  • Rule: run every cell as we go

Setup

Load packages

  • ggplot2: the plotting package (part of the tidyverse)
  • patchwork: combine several plots into one figure
  • ggthemes: extra ready-made themes
  • Missing one? install.packages(c("patchwork", "ggthemes"))
Code
library(ggplot2)
library(patchwork)
library(ggthemes)

options(jupyter.display_mimetypes = c("text/html", "text/plain", "image/png"))
# Figure size in Jupyter only (inches); no effect on saved files
options(repr.plot.width = 9, repr.plot.height = 5, repr.plot.res = 120)

Packages

patchwork - Combines multiple ggplot2 plots into a single figure using arithmetic-style operators - p1 + p2 places plots side by side; p1 / p2 stacks them; | and parentheses allow nested layouts - plot_layout() controls widths, heights, and shared or collected legends (guides = "collect") - plot_annotation() adds an overall title, subtitle, caption, and panel tags (A, B, C…) - Automatically aligns plot panels and axes, which is its main advantage over gridExtra

ggthemes - Supplies extra themes, color/fill scales, and geoms for ggplot2 - Themes mimic well-known publication styles, e.g. theme_economist(), theme_wsj(), theme_fivethirtyeight(), theme_tufte(), theme_few() - Matching scales such as scale_color_colorblind(), scale_fill_tableau(), scale_color_economist() - A few extras like geom_rangeframe() (Tufte-style axes) and geom_tufteboxplot()

In short: patchwork arranges plots; ggthemes styles them.

The data

  • mpg: fuel economy for 234 vehicles (38 models, each in several years and trims), ships with ggplot2
  • Columns we use:
    • displ: engine size (liters)
    • hwy, cty: highway and city miles per gallon
    • class: compact, suv, pickup, …
    • drv: drive train (f front, r rear, 4 four-wheel)
Code
head(mpg)
A tibble: 6 × 11
manufacturer model displ year cyl trans drv cty hwy fl class
<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
audi a4 2.0 2008 4 manual(m6) f 20 31 p compact
audi a4 2.0 2008 4 auto(av) f 21 30 p compact
audi a4 2.8 1999 6 auto(l5) f 16 26 p compact
audi a4 2.8 1999 6 manual(m5) f 18 26 p compact

The grammar of graphics

The big idea

  • Every chart is built from the same small set of components (Wilkinson, 1999; Wickham, 2010)
  • You declare what to show; ggplot2 works out how to draw it
  • Plots are built in layers, joined with +
Component Question it answers Example
data What data frame? mpg
aesthetics Which variable goes to which visual property? aes(x = displ, y = hwy)
geoms What shape represents each observation? geom_point()
stats Any transformation first? counts, bins, smoothers
scales How do values become positions and colors? scale_x_log10()
coordinates What space? coord_cartesian()
facets Split into panels? facet_wrap(~ class)
theme Everything that is not data theme_minimal()

The template

ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) +
  <GEOM_FUNCTION>()
  • ggplot() creates the canvas and sets defaults
  • aes() maps variables to visual properties
  • geom_*() adds a layer that actually draws something
  • + goes at the end of a line, never the start

Building a plot, layer by layer

  • Data alone: blank canvas
  • Add aes(): axes and scales appear
  • Add a geom: the data appears
Code
p0 <- ggplot(mpg)
p1 <- ggplot(mpg, aes(x = displ, y = hwy))
p2 <- p1 + geom_point()

p0 | p1 | p2   # patchwork: "|" places plots side by side (more later)

Plots are objects

  • Store a base plot, add layers later
  • Nothing draws until the object is printed
  • aes(x = displ, y = hwy) is the same as aes(displ, hwy)
Code
p <- ggplot(mpg, aes(displ, hwy))
p + geom_point()

Aesthetics

Mapping a variable to color

  • Add a third variable by mapping it to another aesthetic
  • ggplot2 picks a scale and builds the legend for you
  • Discrete variable: distinct hues; continuous: a gradient
Code
ggplot(mpg, aes(displ, hwy, color = class)) +
  geom_point()

Common aesthetics

Aesthetic Controls Typical use
x, y position almost always
color point color, line color, outlines categories or gradients
fill interior of bars, areas, boxes categories or gradients
size point size a numeric variable
shape point symbol a few categories (max ~6)
alpha transparency (0 to 1) overplotting
linetype solid, dashed, … a few categories
Code
ggplot(mpg, aes(displ, hwy, color = cty, shape = drv)) +
  geom_point(size = 2)

Mapping vs setting

  • Inside aes(): maps a variable (varies with the data, gets a legend)
  • Outside aes(): sets a constant (same for every point)
  • Classic bug: aes(color = "blue") treats "blue" as a one-level category

The bug here is that, on the left, “blue” is treated as a categorical variable with a single category, rather than as a color choice.

Code
wrong <- ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = "blue")) +
  ggtitle('Mapped: aes(color = "blue")')

right <- ggplot(mpg, aes(displ, hwy)) +
  geom_point(color = "blue") +
  ggtitle('Set: color = "blue"')

wrong | right

Global vs local aesthetics

  • In ggplot(): global, inherited by every layer
  • In a geom_*(): local, that layer only
  • Left: color only on points, one trend line; right: color is global, one line per group

Notice that because we’re using the aesthetic feature inside the geom_point() section, it has a local effect—it’s only applied to the points, not the lines.

Code
local_color <- ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = drv)) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE)

global_color <- ggplot(mpg, aes(displ, hwy, color = drv)) +
  geom_point() +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE)

local_color | global_color

Geoms

Choosing a geom

What you are showing Geoms
One continuous variable geom_histogram(), geom_density()
One categorical variable geom_bar()
Two continuous variables geom_point(), geom_smooth()
Continuous over time geom_line()
Categorical vs continuous geom_boxplot(), geom_violin(), geom_jitter()
Precomputed values geom_col()

Distributions of one variable

  • Histogram: counts per bin; always choose binwidth or bins
  • Density: smoothed histogram, good for comparing shapes
  • Note: fill and color here are set, not mapped
Code
h <- ggplot(mpg, aes(hwy)) +
  geom_histogram(binwidth = 2, fill = "steelblue", color = "white")

d <- ggplot(mpg, aes(hwy)) +
  geom_density(fill = "steelblue", alpha = 0.5)

h | d

Bars: geom_bar() vs geom_col()

  • geom_bar(): counts rows for you (uses a stat)
  • geom_col(): bar height is already a column in the data
  • reorder(x, y) sorts bars by value: easier to read

Left plot (counts): You only give an x variable. geom_bar() counts how many cars fall in each class and draws those counts as bar heights. The counting happens inside ggplot.

Right plot (means): 1. aggregate() computes the mean hwy for each class, giving a small table with one row per class. 2. geom_col() draws bars whose heights are those precomputed means. ggplot does no counting or summarizing; it plots the numbers as given. 3. reorder(class, hwy) orders the x-axis by mean hwy, so bars rise from lowest to highest instead of sitting in alphabetical order.

counts | means: puts the two plots side by side.

In short, use geom_bar() when ggplot should count rows for you, and geom_col() when you have already computed the heights.

Code
# Bar plot of car counts per class using geom_bar()
counts <- ggplot(mpg, aes(class)) +    
  geom_bar()

# Calculate average highway mpg for each class
avg <- aggregate(hwy ~ class, data = mpg, FUN = mean)   

# Display the table of mean highway mpg per class
print(avg)   

# Bar plot of mean highway mpg per class using geom_col(), sorted by mean
means <- ggplot(avg, aes(x = reorder(class, hwy), y = hwy)) +  
  geom_col() +
  labs(x = "class", y = "mean hwy")

# Show the two plots side by side
counts | means
       class      hwy
1    2seater 24.80000
2    compact 28.29787
3    midsize 27.29268
4    minivan 22.36364
5     pickup 16.87879
6 subcompact 28.14286
7        suv 18.12903

Visualizing categorical vs continuous variables

  • Boxplot: Summarizes how a continuous variable (like highway mpg) varies across categories (like drivetrain). The thick middle line shows the median, the box edges show the 25th and 75th percentiles (the “quartiles”), and the “whiskers” and dots display outliers. Good for quickly comparing group medians and spread.
  • Violin plot: Like a boxplot, but adds a rotated density curve to show the full shape of the data distribution for each category (are values clumped, spread out, or multi-peaked?). This helps you spot features boxplots might hide.
  • Raw data points with geom_jitter(): When the number of points is not too large, you can add individual dots. geom_jitter() adds a little horizontal “noise” so overlapping points are easier to see. This lets you visualize every data observation along with the summary.
Code
b <- ggplot(mpg, aes(drv, hwy)) +
  geom_boxplot()

head(mpg[, c("drv", "hwy")])

v <- ggplot(mpg, aes(drv, hwy)) +
  geom_violin(fill = "gray90") +
  geom_jitter(width = 0.15, alpha = 0.4)

b | v
A tibble: 6 × 2
drv hwy
<chr> <int>
f 29
f 29
f 31
f 30
f 26
f 26

Change over time: geom_line()

  • economics: monthly US economic data (ships with ggplot2)
  • aes() accepts expressions: rescale on the fly
  • Lines use linewidth; points use size
Code
ggplot(economics, aes(date, unemploy / 1000)) +
  geom_line(color = "firebrick", linewidth = 0.8) +
  labs(y = "Unemployed (millions)")

Stacking layers

  • Layers draw in order: later layers sit on top
  • geom_smooth() adds a trend line and confidence band
    • method = "lm": straight line; "loess": flexible curve
  • Pattern: raw data (faded) + summary on top
Code
ggplot(mpg, aes(displ, hwy)) +
  geom_point(alpha = 0.4) +
  geom_smooth(method = "loess", formula = y ~ x, color = "black")

Overplotting

  • mpg values are rounded, so many points sit on top of each other
  • Fixes: transparency (alpha), random nudges (geom_jitter()), or sized counts (geom_count())
Code
# Create a ggplot base object mapping city mpg to x and highway mpg to y
p <- ggplot(mpg, aes(cty, hwy))

# Compare three ways to handle overplotting (many points drawn on top of each other):
# 1. Simple scatter plot
# 2. Jittered scatter (points nudged to reduce overlap)
# 3. Count plot (point size shows number of overlapping points)
p + geom_point() + ggtitle("geom_point") |                                   # basic scatter plot
  p + geom_jitter(width = 0.3, height = 0.3, alpha = 0.5) + ggtitle("geom_jitter") |  # scatter with jitter & alpha
  p + geom_count() + ggtitle("geom_count")                                           # point size = number of overlapping cases

Facets

Small multiples

  • Split one plot into panels, one per group
  • facet_wrap(~ var): one variable, wrapped into a grid
  • facet_grid(rows ~ cols): two variables, a full grid
  • Often clearer than cramming groups into colors
Code
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~ class, nrow = 2)

Code
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_grid(drv ~ cyl)

Shared vs free axes

  • Default: all panels share axes, so panels compare directly
  • scales = "free", "free_x", "free_y": each panel gets its own range
  • Use free scales when variables have different units; state it clearly, readers assume shared axes
  • Same idea as sharex / sharey in matplotlib
Code
ggplot(economics_long, aes(date, value)) +
  geom_line() +
  facet_wrap(~ variable, scales = "free_y")

Labels, scales, and coordinates

Labels with labs()

  • One call for title, subtitle, axes, legend titles, caption
  • Title states the takeaway, not the variable names
  • Axis labels include units
  • Legend title is set by the aesthetic name (color = ...)
Code
ggplot(mpg, aes(displ, hwy, color = drv)) +
  geom_point() +
  labs(
    title    = "Larger engines get fewer miles per gallon",
    subtitle = "234 vehicles, 1999 and 2008",
    x        = "Engine displacement (L)",
    y        = "Highway fuel economy (mpg)",
    color    = "Drive train",
    caption  = "Source: EPA, via ggplot2::mpg"
  )

Scales

  • Every aesthetic has a scale: scale_<aesthetic>_<type>()
    • scale_x_log10(), scale_y_continuous(limits, breaks, labels)
    • scale_color_manual(), scale_fill_viridis_d(), …
  • Log scales for data spanning orders of magnitude
  • scales package formats labels: label_dollar(), label_percent(), label_comma()
Code
ggplot(diamonds, aes(carat, price)) +
  geom_point(alpha = 0.05) +
  scale_x_log10() +
  scale_y_log10(labels = scales::label_dollar())

Coordinates

  • coord_cartesian(xlim = ...): zoom without dropping data
    • vs scale_x_continuous(limits = ...): removes data outside the limits before any stat runs
    • Result: a different smoother (or boxplot), plus a “Removed n rows” warning
  • coord_fixed(): 1 unit on x equals 1 unit on y
  • coord_polar(): circular plots (used for the color wheel in the Color section)
Code
p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point(alpha = 0.4) +
  geom_smooth(method = "loess", formula = y ~ x, color = "black")

p + scale_x_continuous(limits = c(2, 5)) + ggtitle("scale limits: data dropped, fit changes") |
  p + coord_cartesian(xlim = c(2, 5)) + ggtitle("coord_cartesian: zoom only, same fit")

Horizontal bars

  • Long category labels read better on the y axis
  • Modern approach: map the category to y; the geom works out the orientation
  • coord_flip() does the same by swapping axes; it is superseded (ggplot2 3.3.0+) but common in older code
Code
ggplot(mpg, aes(y = class)) +
  geom_bar()

# Legacy equivalent, still seen in older code:
# ggplot(mpg, aes(class)) + geom_bar() + coord_flip()

Color

Color theory basics

  • The color wheel maps the spectrum onto a circle (Newton, Opticks, 1704)
  • Two common wheels:
    • RYB (red, yellow, blue): painters, mixing pigment
    • RGB (red, green, blue): screens, mixing light; what we use
  • Warm colors: red through yellow (sun, energy)
  • Cool colors: green through purple (water, calm)

An RGB color wheel, drawn with ggplot2

  • 12 hues, 30 degrees apart, built with hsv()
  • scale_fill_identity(): use the hex strings as the colors themselves
  • coord_polar() bends the bar chart into a wheel
Code
wheel <- data.frame(hue = seq(0, 330, by = 30))
wheel$hex <- hsv(wheel$hue / 360, s = 1, v = 1)

ggplot(wheel, aes(x = factor(hue), y = 1, fill = hex)) +
  geom_col(width = 1, color = "white") +
  geom_text(aes(y = 0.8, label = hex), size = 3) +
  scale_fill_identity() +
  coord_polar() +
  theme_void()

Color schemes

Scheme Rule Effect
Complementary opposite sides of the wheel high contrast, high impact
Analogous 3 neighbors harmonious; pick one dominant, others as accents
Monochromatic one hue, varied shade and tint subtle, conservative
Triadic / tetradic 3 or 4 evenly spaced bold; needs balancing
Code
swatch <- function(hex, title) {
  ggplot(data.frame(x = seq_along(hex), hex = hex), aes(x, 1, fill = hex)) +
    geom_tile(color = "white", linewidth = 2) +
    geom_text(aes(label = hex), size = 3) +
    scale_fill_identity() +
    labs(title = title) +
    theme_void()
}

(swatch(hsv(c(200, 20) / 360, 0.8, 0.9), "Complementary") |
   swatch(hsv(c(170, 200, 230) / 360, 0.8, 0.9), "Analogous")) /
(swatch(hsv(200 / 360, c(0.3, 0.6, 0.9), c(1, 0.8, 0.5)), "Monochromatic") |
   swatch(hsv(c(200, 320, 80) / 360, 0.8, 0.9), "Triadic"))

Hue, saturation, luminance

  • Hue: which color (position on the wheel)
  • Saturation: intensity or purity (gray to vivid)
  • Luminance: brightness (dark to light)
  • People readily perceive changes in saturation and luminance: use them to show order
  • Use hue to show categories
  • R builds colors from these: hsv(), hcl() (perceptually even steps)

Hexadecimal color codes

  • Format: #RRGGBB, two hex digits each for red, green, blue
  • Hexadecimal is base 16: digits 0-9 then a-f
  • Each channel: 00 to ff, i.e. 0 to 255 (16 x 16 = 256 levels)
  • #000000 black (no light), #ffffff white (all channels full), #ff0000 pure red
Code
rgb(52, 246, 255, maxColorValue = 255)   # channels to hex
col2rgb(c("#34f6ff", "steelblue"))       # hex or name to channels
'#34F6FF'
A matrix: 3 × 2 of type int
red 52 70
green 246 130
blue 255 180

Named colors

  • R has 657 built-in names: colors()
  • Many come in numbered shades: gray10 to gray90, deeppink1 to deeppink4
  • Most names also work in Python/matplotlib (without the number suffixes)
  • Hex codes work everywhere: fill = "#34f6ff"
Code
grep("blue", colors(), value = TRUE)[1:12]

ggplot(mpg, aes(hwy)) +
  geom_histogram(binwidth = 2, fill = "#34f6ff", color = "black")
  1. 'aliceblue'
  2. 'blue'
  3. 'blue1'
  4. 'blue2'
  5. 'blue3'
  6. 'blue4'
  7. 'blueviolet'
  8. 'cadetblue'
  9. 'cadetblue1'
  10. 'cadetblue2'
  11. 'cadetblue3'
  12. 'cadetblue4'

Palettes: three types

  • Sequential: ordered data, low to high (light to dark)
  • Diverging: meaningful midpoint (e.g. above / below average)
  • Qualitative: unordered categories (distinct hues)
  • Match the palette to the data type, not to taste
  • ColorBrewer palettes are built into ggplot2; below, colorblind-safe subset:
    • top: sequential; middle: qualitative; bottom: diverging
Code
options(repr.plot.height = 8)   # tall figure for this one
RColorBrewer::display.brewer.all(colorblindFriendly = TRUE)

Discrete palettes

  • scale_color_* for points and lines; scale_fill_* for areas
  • _brewer(): ColorBrewer; _viridis_d(): viridis; _manual(): your own
  • Name the values in _manual() so colors stick to categories
Code
options(repr.plot.height = 5)   # Set plot height back to default

# Create base scatter plot: engine displacement vs highway mpg, colored by drive type
p <- ggplot(mpg, aes(displ, hwy, color = drv)) + 
  geom_point(size = 2)

# Apply three discrete color palettes and combine them for visual comparison:
# 1. ColorBrewer "Dark2" palette
# 2. viridis discrete palette
# 3. manual assignment of colors to each drv (drive type)
p + scale_color_brewer(palette = "Dark2") + ggtitle("brewer: Dark2") |
  p + scale_color_viridis_d() + ggtitle("viridis_d") |
  p + scale_color_manual(values = c("4" = "#d95f02", f = "#1b9e77", r = "#7570b3")) +
    ggtitle("manual")

Continuous palettes

  • _viridis_c(), _distiller() (ColorBrewer), _gradient(low, high)
  • _gradient2(low, mid, high, midpoint) for diverging data
  • Suffix rule: _d discrete, _c continuous
Code
# Create a raster plot of the faithfuld dataset, filling by density
p <- ggplot(faithfuld, aes(waiting, eruptions, fill = density)) + 
  geom_raster()

# Show two versions side-by-side:
# - Left: viridis continuous color scale (colorblind-friendly, perceptually uniform)
# - Right: custom gradient from white to blue (hex #08519c)
p + scale_fill_viridis_c() + ggtitle("viridis_c") |
  p + scale_fill_gradient(low = "white", high = "#08519c") + ggtitle("gradient")

Accessibility

  • About 1 in 12 men has red-green color vision deficiency
  • viridis: colorblind-safe, perceptually even, survives grayscale printing
  • Never rely on red vs green alone
  • Redundant encoding: map the same variable to color and shape
  • Check palettes at colorbrewer2.org (“colorblind safe” filter)
Code
ggplot(mpg, aes(displ, hwy, color = drv, shape = drv)) +
  geom_point(size = 2) +
  scale_color_viridis_d(end = 0.85)

Themes

What a theme controls

  • Everything that is not data: background, grid lines, fonts, axes, legend, facet strips
  • Never changes the data mapping
  • Three levels of control:
    • Complete theme: theme_bw(), theme_minimal(), …
    • Tweaks: theme(...)
    • Session default: theme_set(...)

Built-in complete themes

Code
p <- ggplot(mpg, aes(displ, hwy)) + geom_point()

themes <- list(
  "theme_gray (default)" = theme_gray(),
  "theme_bw"      = theme_bw(),
  "theme_minimal" = theme_minimal(),
  "theme_classic" = theme_classic(),
  "theme_dark"    = theme_dark(),
  "theme_void"    = theme_void()
)

plots <- lapply(names(themes), function(n) p + themes[[n]] + ggtitle(n))
wrap_plots(plots, ncol = 3)

Extension themes: ggthemes

  • Mimic publications and designers: FiveThirtyEight, The Economist, Tufte, WSJ
  • Other packages: hrbrthemes, ggpubr (publication-ready)
Code
p + theme_fivethirtyeight() + ggtitle("fivethirtyeight") |
  p + theme_economist() + ggtitle("economist") |
  p + theme_tufte() + ggtitle("tufte")

Customizing with theme()

  • Syntax: theme(<element name> = element_*(...))
Function Modifies Common arguments
element_text() titles, axis labels, legend text size, face, color, angle, family
element_line() grid lines, axis lines, ticks color, linewidth, linetype
element_rect() backgrounds, borders fill, color
element_blank() anything removes it
  • Element names inherit: text > axis.text > axis.text.x
  • Portable font families: "sans", "serif", "mono"; named fonts depend on the OS
Code
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  theme(
    axis.title         = element_text(size = 16, family = "serif", color = "blue"),
    axis.text          = element_text(size = 12),
    panel.grid.major.x = element_blank(),
    panel.grid.minor   = element_blank()
  )

Tweaking a complete theme

  • Start from a complete theme, then add theme() tweaks
  • Order matters: a complete theme added after theme() erases the tweaks
  • Two tweaks you will use constantly:
    • rotate crowded labels: element_text(angle = 45, hjust = 1)
    • move or hide the legend: legend.position = "top", "bottom", "none"
Code
ggplot(mpg, aes(manufacturer, fill = drv)) +
  geom_bar() +
  theme_minimal() +
  theme(
    axis.text.x     = element_text(angle = 45, hjust = 1),
    legend.position = "top"
  )

Save and reuse your own theme

  • Wrap it in a function: reusable, adjustable base_size
  • Add it to any plot like a built-in theme
  • Course expectation: build your own theme and use it consistently in all your visualizations
Code
theme_lecture <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      plot.title       = element_text(face = "bold"),
      axis.title       = element_text(color = "gray30"),
      panel.grid.minor = element_blank(),
      legend.position  = "bottom"
    )
}

ggplot(mpg, aes(displ, hwy, color = drv)) +
  geom_point() +
  theme_lecture()

Set a session default: theme_set()

  • Applies to every plot after it
  • Returns the previous theme, so you can restore it
Code
old <- theme_set(theme_lecture(base_size = 14))

ggplot(mpg, aes(hwy)) +
  geom_histogram(binwidth = 2)

theme_set(old)   # restore the default

Layout and export

Combining plots: patchwork

  • p1 | p2: side by side; p1 / p2: stacked; parentheses to nest
  • plot_annotation(): overall title, panel tags (A, B, C)
  • Facets: one plot split by a variable; patchwork: different plots together
  • Same role as plt.subplots() in matplotlib
Code
a <- ggplot(mpg, aes(displ, hwy)) + geom_point()
b <- ggplot(mpg, aes(hwy)) + geom_histogram(binwidth = 2)
c <- ggplot(mpg, aes(drv, hwy)) + geom_boxplot()

(a | b) / c +
  plot_annotation(title = "Highway fuel economy, three views", tag_levels = "A")

Size and aspect ratio

  • Size and shape change how a plot reads: set them on purpose
  • Golden ratio (about 1.618 : 1, width : height) is a pleasing default
  • Jupyter display: options(repr.plot.width = ..., repr.plot.height = ...)
  • Panel shape: theme(aspect.ratio = 1 / 1.618)
  • Text size is absolute: a small figure makes text look big, and vice versa

Saving: ggsave()

  • Pass the plot object explicitly (default is the last plot shown)
  • width / height in inches by default (units = "cm" also works)
  • PNG for slides and web (dpi = 300); PDF or SVG (vector) for print
Code
golden <- (1 + sqrt(5)) / 2
w <- 7

p_final <- ggplot(mpg, aes(displ, hwy)) + geom_point() + theme_lecture()

ggsave("mpg-scatter.png", p_final, width = w, height = w / golden, dpi = 300)
ggsave("mpg-scatter.pdf", p_final, width = w, height = w / golden)

Putting it together

A polished plot

  • Faded raw data + loess summary (the relationship curves, as we saw earlier)
  • Trend fit without the two-seaters: a layer can take its own data, so a few outliers do not bend the summary
  • Colorblind-safe palette with readable legend labels
  • Ring a subset with a second geom_point() layer on filtered data
  • annotate() adds one-off text and an arrow, not tied to the data
  • Takeaway title, units, source, custom theme
Code
# Subset the data: two-seaters vs everyone else
two_seaters <- subset(mpg, class == "2seater")
others      <- subset(mpg, class != "2seater")

# Build the plot step-by-step
ggplot(mpg, aes(displ, hwy)) +
  # Raw data points, colored by drive type, faded for a subtle backdrop
  geom_point(aes(color = drv), alpha = 0.7, size = 2) +
  # Add a loess smooth trend line for all classes except two-seaters
  geom_smooth(
    data = others, method = "loess", formula = y ~ x, se = FALSE,
    color = "gray40", linewidth = 0.7
  ) +
  # Highlight the two-seat sports cars with outlined, larger points
  geom_point(
    data = two_seaters, shape = 21, size = 4.5,
    stroke = 0.8, color = "black"
  ) +
  # Add annotation text describing the two-seaters
  annotate(
    "text", x = 6.35, y = 34, size = 3.5,
    label = "Two-seaters (Corvette): big engines,\nlight bodies"
  ) +
  # Add an annotation arrow pointing from the text to the two-seater data
  annotate(
    "segment", x = 6.35, y = 32, xend = 6.2, yend = 27.5,
    arrow = arrow(length = unit(0.15, "cm")), color = "gray30"
  ) +
  # Set a colorblind-safe palette and clarify legend labels
  scale_color_brewer(
    palette = "Dark2",
    labels = c("4" = "4WD", f = "Front", r = "Rear")
  ) +
  # Add informative title, axis labels, legend label, and caption
  labs(
    title    = "Bigger engines burn more fuel",
    subtitle = "Highway fuel economy vs engine size, 234 vehicles",
    x = "Engine displacement (L)", y = "Highway (mpg)",
    color = "Drive", caption = "Source: EPA, via ggplot2::mpg"
  ) +
  # Apply a custom lecture theme for consistent style
  theme_lecture()

Recap

  • Core: data + aes() + geom, layered with +
  • Map variables inside aes(); set constants outside
  • Pick the geom by what you are showing
  • Facets for group comparisons; watch shared vs free axes
  • Labels: takeaway title, units on axes
  • Palette type matches data type; stay colorblind-safe
  • Themes for polish; build one, reuse it everywhere
  • Save with ggsave() at a deliberate size

Python equivalents (reference)

ggplot2 Python
grammar (aes + geoms) plotnine (same grammar), seaborn
theme_bw(), complete themes plt.style.use("..."), sns.set_theme()
theme(...) tweaks mpl.rcParams[...]
saved theme function .mplstyle file / matplotlibrc
theme_set() plt.style.use() at top of script
facet_wrap() sns.relplot(col=...), FacetGrid
patchwork plt.subplots()
scale_color_brewer() sns.set_palette("Dark2")
ggsave() fig.savefig()

Resources