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 filesoptions(repr.plot.width =9, repr.plot.height =5, repr.plot.res =120)
Warning message:
“package ‘ggplot2’ was built under R version 4.4.3”
Warning message:
“package ‘patchwork’ was built under R version 4.4.1”
Warning message:
“package ‘ggthemes’ was built under R version 4.4.3”
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)
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
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.
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
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.
# Bar plot of car counts per class using geom_bar()counts <-ggplot(mpg, aes(class)) +geom_bar()# Calculate average highway mpg for each classavg <-aggregate(hwy ~ class, data = mpg, FUN = mean) # Display the table of mean highway mpg per classprint(avg) # Bar plot of mean highway mpg per class using geom_col(), sorted by meanmeans <-ggplot(avg, aes(x =reorder(class, hwy), y = hwy)) +geom_col() +labs(x ="class", y ="mean hwy")# Show the two plots side by sidecounts | means
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.
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)
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())
# Create a ggplot base object mapping city mpg to x and highway mpg to yp <-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
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)
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")
Warning message:
“Removed 58 rows containing non-finite outside the scale range
(`stat_smooth()`).”
Warning message:
“Removed 58 rows containing missing values or values outside the scale range
(`geom_point()`).”
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
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
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()
options(repr.plot.height =8) # tall figure for this oneRColorBrewer::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
options(repr.plot.height =5) # Set plot height back to default# Create base scatter plot: engine displacement vs highway mpg, colored by drive typep <-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")
_gradient2(low, mid, high, midpoint) for diverging data
Suffix rule: _d discrete, _c continuous
# Create a raster plot of the faithfuld dataset, filling by densityp <-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
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
golden <- (1+sqrt(5)) /2w <-7p_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
# Subset the data: two-seaters vs everyone elsetwo_seaters <-subset(mpg, class =="2seater")others <-subset(mpg, class !="2seater")# Build the plot step-by-stepggplot(mpg, aes(displ, hwy)) +# Raw data points, colored by drive type, faded for a subtle backdropgeom_point(aes(color = drv), alpha =0.7, size =2) +# Add a loess smooth trend line for all classes except two-seatersgeom_smooth(data = others, method ="loess", formula = y ~ x, se =FALSE,color ="gray40", linewidth =0.7 ) +# Highlight the two-seat sports cars with outlined, larger pointsgeom_point(data = two_seaters, shape =21, size =4.5,stroke =0.8, color ="black" ) +# Add annotation text describing the two-seatersannotate("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 dataannotate("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 labelsscale_color_brewer(palette ="Dark2",labels =c("4"="4WD", f ="Front", r ="Rear") ) +# Add informative title, axis labels, legend label, and captionlabs(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 styletheme_lecture()
Recap
Core: data + aes() + geom, layered with +
Map variables insideaes(); 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