The grammar of graphics, color, and themes
theme(), your own reusable themeggplot2: the plotting package (part of the tidyverse)patchwork: combine several plots into one figureggthemes: extra ready-made themesinstall.packages(c("patchwork", "ggthemes"))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.
mpg: fuel economy for 234 vehicles (38 models, each in several years and trims), ships with ggplot2displ: engine size (liters)hwy, cty: highway and city miles per gallonclass: compact, suv, pickup, …drv: drive train (f front, r rear, 4 four-wheel)| 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 |
+| 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() |
ggplot() creates the canvas and sets defaultsaes() maps variables to visual propertiesgeom_*() adds a layer that actually draws something+ goes at the end of a line, never the startaes(): axes and scales appearaes(x = displ, y = hwy) is the same as aes(displ, hwy)| 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 |
aes(): maps a variable (varies with the data, gets a legend)aes(): sets a constant (same for every point)aes(color = "blue") treats "blue" as a one-level categoryThe bug here is that, on the left, “blue” is treated as a categorical variable with a single category, rather than as a color choice.
ggplot(): global, inherited by every layergeom_*(): local, that layer onlyNotice 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.
| 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() |
binwidth or binsfill and color here are set, not mappedgeom_bar() vs geom_col()geom_bar(): counts rows for you (uses a stat)geom_col(): bar height is already a column in the datareorder(x, y) sorts bars by value: easier to readLeft 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 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

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.geom_line()economics: monthly US economic data (ships with ggplot2)aes() accepts expressions: rescale on the flylinewidth; points use sizegeom_smooth() adds a trend line and confidence band
method = "lm": straight line; "loess": flexible curvempg values are rounded, so many points sit on top of each otheralpha), random nudges (geom_jitter()), or sized counts (geom_count())# 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
facet_wrap(~ var): one variable, wrapped into a gridfacet_grid(rows ~ cols): two variables, a full gridscales = "free", "free_x", "free_y": each panel gets its own rangesharex / sharey in matplotliblabs()color = ...)scale_<aesthetic>_<type>()
scale_x_log10(), scale_y_continuous(limits, breaks, labels)scale_color_manual(), scale_fill_viridis_d(), …scales package formats labels: label_dollar(), label_percent(), label_comma()coord_cartesian(xlim = ...): zoom without dropping data
scale_x_continuous(limits = ...): removes data outside the limits before any stat runscoord_fixed(): 1 unit on x equals 1 unit on ycoord_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")
y; the geom works out the orientationcoord_flip() does the same by swapping axes; it is superseded (ggplot2 3.3.0+) but common in older codehsv()scale_fill_identity(): use the hex strings as the colors themselvescoord_polar() bends the bar chart into a wheel| 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 |
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"))
hsv(), hcl() (perceptually even steps)#RRGGBB, two hex digits each for red, green, blue0-9 then a-f00 to ff, i.e. 0 to 255 (16 x 16 = 256 levels)#000000 black (no light), #ffffff white (all channels full), #ff0000 pure redcolors()gray10 to gray90, deeppink1 to deeppink4fill = "#34f6ff"scale_color_* for points and lines; scale_fill_* for areas_brewer(): ColorBrewer; _viridis_d(): viridis; _manual(): your own_manual() so colors stick to categoriesoptions(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")
_viridis_c(), _distiller() (ColorBrewer), _gradient(low, high)_gradient2(low, mid, high, midpoint) for diverging data_d discrete, _c continuous# 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")
theme_bw(), theme_minimal(), …theme(...)theme_set(...)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)
ggthemeshrbrthemes, ggpubr (publication-ready)theme()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 |
text > axis.text > axis.text.x"sans", "serif", "mono"; named fonts depend on the OStheme() tweakstheme() erases the tweakselement_text(angle = 45, hjust = 1)legend.position = "top", "bottom", "none"base_sizetheme_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()
theme_set()patchworkp1 | p2: side by side; p1 / p2: stacked; parentheses to nestplot_annotation(): overall title, panel tags (A, B, C)plt.subplots() in matplotliboptions(repr.plot.width = ..., repr.plot.height = ...)theme(aspect.ratio = 1 / 1.618)ggsave()width / height in inches by default (units = "cm" also works)dpi = 300); PDF or SVG (vector) for printdata, so a few outliers do not bend the summarygeom_point() layer on filtered dataannotate() adds one-off text and an arrow, not tied to the data# 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()
aes() + geom, layered with +aes(); set constants outsideggsave() at a deliberate size| 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() |