ggplot2
ggplot2 builds a plot from layers. You name the data, map columns to aesthetics inside aes(),
add one or more geoms, then adjust scales, labels, and the theme. Every example below runs in
ggplot2 4.0.3 and writes its figure with ggsave().
Quick reference
Section titled “Quick reference”| Layer | Function | Use |
|---|---|---|
| Points | geom_point() |
Scatter, volcano, MA |
| Labels | geom_text(), ggrepel::geom_text_repel() |
Gene names on points |
| Boxes | geom_boxplot() |
Group comparisons |
| Violins | geom_violin() |
Distribution shape |
| Bars | geom_col() |
Heights already in the data |
| Bars | geom_bar() |
Counts from raw rows |
| Histogram | geom_histogram() |
One distribution |
| Density | geom_density() |
Smoothed distribution |
| Lines | geom_line() |
Ordered x such as time |
| Summaries | stat_summary() |
Mean and error bars from raw rows |
| Error bars | geom_errorbar(aes(ymin = , ymax = )) |
Bars from a summary table |
| Trend line | geom_smooth(method = "lm") |
Fitted line with a confidence band |
| Tiles | geom_tile() |
Small heatmap from a long table |
| Dot plot | geom_point(aes(size = , color = )) |
Enrichment results |
| Reference lines | geom_hline(), geom_vline() |
Thresholds |
| Panels | facet_wrap(), facet_grid() |
Split by one or two variables |
| Scale | Function | Use |
|---|---|---|
| Discrete colors | scale_color_manual(values = ) |
Fixed color per level |
| Fill colors | scale_fill_manual(values = ) |
Box and bar fills |
| Continuous colors | scale_color_viridis_c() |
Color by a number |
| Diverging fill | scale_fill_gradient2(midpoint = 0) |
Values on both sides of zero |
| Point size | scale_size_area() |
Size proportional to a count |
| Log axis | scale_x_log10(), scale_y_log10() |
Counts and mean expression |
| Axis range | coord_cartesian(ylim = ) |
Zoom without dropping data |
| Out of range | oob = scales::squish |
Cap a color gradient |
scale_y_continuous(limits = ) removes the rows outside the limits before a box or a mean is
computed. coord_cartesian() only zooms, so the statistics stay the same.
The first table is a differential expression result for 2,000 simulated genes. The p-value comes from a Wald statistic, so genes with a large fold change and a high mean count are the most significant, as in a real DESeq2 run.
library(ggplot2)library(dplyr)library(tidyr)
set.seed(42)dir.create("outputs", showWarnings = FALSE)
n_genes <- 2000n_de <- 150degs <- tibble( gene = sprintf("GENE%04d", seq_len(n_genes)), base_mean = 10^runif(n_genes, 1, 4.5), log2fc = c( rnorm(n_genes - n_de, 0, 0.3), sample(c(-1, 1), n_de, replace = TRUE) * runif(n_de, 0.8, 4) ), lfc_se = 0.25 + 2 / sqrt(base_mean)) |> mutate( pvalue = 2 * pnorm(-abs(log2fc / lfc_se)), padj = p.adjust(pvalue, method = "BH"), status = case_when( padj < 0.05 & log2fc > 1 ~ "Up", padj < 0.05 & log2fc < -1 ~ "Down", .default = "NS" ) )print(degs, n = 3)# A tibble: 2,000 × 7 gene base_mean log2fc lfc_se pvalue padj status <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>1 GENE0001 15916. 0.698 0.266 0.00870 0.117 NS2 GENE0002 19044. 0.157 0.264 0.552 1.000 NS3 GENE0003 100. 0.291 0.450 0.517 1.000 NS# ℹ 1,997 more rowsThe second table holds log2 CPM values for three genes in 12 control and 12 treated samples, in long format with one row per gene and sample.
expr <- expand_grid( gene = c("TP53", "BRCA1", "EGFR"), condition = c("Control", "Treated"), replicate = 1:12) |> mutate( sample = paste0(condition, "_", replicate), base = c(TP53 = 9, BRCA1 = 7, EGFR = 10)[gene], shift = case_when( gene == "EGFR" & condition == "Treated" ~ 1.5, gene == "BRCA1" & condition == "Treated" ~ -0.8, .default = 0 ), log2_cpm = rnorm(n(), mean = base + shift, sd = 0.6) ) |> select(gene, sample, condition, log2_cpm)print(expr, n = 3)# A tibble: 72 × 4 gene sample condition log2_cpm <chr> <chr> <chr> <dbl>1 TP53 Control_1 Control 8.592 TP53 Control_2 Control 8.523 TP53 Control_3 Control 8.76# ℹ 69 more rowsVolcano plot
Section titled “Volcano plot”Map the fold change to x and the adjusted p-value to y, then color by the status column. A
named vector in scale_color_manual() ties each color to a level, so the colors stay right
when a level is missing.
status_colors <- c(Down = "#3C5488", NS = "grey70", Up = "#DC0000")
volcano <- ggplot(degs, aes(x = log2fc, y = -log10(padj), color = status)) + geom_point(size = 1, alpha = 0.6) + geom_hline(yintercept = -log10(0.05), linetype = "dashed") + geom_vline(xintercept = c(-1, 1), linetype = "dashed") + scale_color_manual(values = status_colors) + labs( x = "log2 fold change", y = "-log10 adjusted p-value", color = NULL ) + theme_minimal(base_size = 13)
ggsave( "outputs/ggplot2-volcano.png", volcano, width = 6, height = 4.5, dpi = 150, bg = "white")
Label selected points
Section titled “Label selected points”ggrepel moves labels apart so they do not overlap the points or each other. Pass a filtered
table to the label layer so only the top genes get a label. Set seed to get the same
layout on every run.
library(ggrepel)
top_genes <- degs |> filter(status != "NS") |> slice_min(padj, n = 8)
volcano_labelled <- volcano + geom_text_repel( data = top_genes, aes(label = gene), size = 3, color = "black", box.padding = 0.6, min.segment.length = 0, seed = 42, max.overlaps = Inf )
ggsave( "outputs/ggplot2-volcano-labels.png", volcano_labelled, width = 6, height = 4.5, dpi = 150, bg = "white")
MA plot with a log axis and a color gradient
Section titled “MA plot with a log axis and a color gradient”scale_x_log10() spreads the mean counts across four orders of magnitude. A few genes with
tiny p-values would take the whole color range, so limits caps the gradient at 20 and
oob = scales::squish paints the larger values with the top color.
ma_plot <- ggplot( degs, aes(x = base_mean, y = log2fc, color = -log10(padj))) + geom_point(size = 0.8) + geom_hline(yintercept = 0) + scale_x_log10(labels = scales::label_comma()) + scale_color_viridis_c( option = "magma", direction = -1, limits = c(0, 20), oob = scales::squish ) + labs( x = "Mean count", y = "log2 fold change", color = "-log10\nadj. p" ) + theme_bw(base_size = 13)
ggsave( "outputs/ggplot2-ma.png", ma_plot, width = 6, height = 4.5, dpi = 150, bg = "white")
Boxplot with the samples on top
Section titled “Boxplot with the samples on top”fill splits each gene into one box per condition. position_jitterdodge() places the points
over the matching box. outliers = FALSE stops the box from drawing the outliers a second
time; older code uses outlier.shape = NA for the same effect.
condition_fill <- c(Control = "#4DBBD5", Treated = "#E64B35")
box <- ggplot(expr, aes(x = gene, y = log2_cpm, fill = condition)) + geom_boxplot(outliers = FALSE, width = 0.6) + geom_point( position = position_jitterdodge( jitter.width = 0.15, dodge.width = 0.6, seed = 42 ), size = 1.2, alpha = 0.6 ) + scale_fill_manual(values = condition_fill) + labs(x = NULL, y = "log2 CPM", fill = NULL) + theme_classic(base_size = 13) + theme(legend.position = "top")
ggsave( "outputs/ggplot2-boxplot.png", box, width = 6, height = 4.5, dpi = 150, bg = "white")
Violin with a boxplot inside
Section titled “Violin with a boxplot inside”The violin shows the shape of each distribution and the narrow box shows the quartiles.
Both layers must use the same dodge width to line up. ggplot2 4.0 deprecates the
draw_quantiles argument of geom_violin(); set quantile.linetype instead to draw the
quartile lines on the violin itself.
violin <- ggplot(expr, aes(x = gene, y = log2_cpm, fill = condition)) + geom_violin(alpha = 0.7, position = position_dodge(width = 0.9)) + geom_boxplot( width = 0.12, position = position_dodge(width = 0.9), outliers = FALSE, show.legend = FALSE ) + scale_fill_manual(values = condition_fill) + labs(x = NULL, y = "log2 CPM", fill = NULL) + theme_classic(base_size = 13)
ggsave( "outputs/ggplot2-violin.png", violin, width = 6, height = 4.5, dpi = 150, bg = "white")
Histogram
Section titled “Histogram”Set binwidth in data units rather than a number of bins, so the bars mean the same thing
from one dataset to the next.
histogram <- ggplot(degs, aes(x = log2fc)) + geom_histogram(binwidth = 0.2, fill = "#3C5488", color = "white") + geom_vline(xintercept = 0, linetype = "dashed", color = "#DC0000") + labs(x = "log2 fold change", y = "Genes") + theme_minimal(base_size = 13)
ggsave( "outputs/ggplot2-histogram.png", histogram, width = 6, height = 4, dpi = 150, bg = "white")
Density
Section titled “Density”Filter to one gene before you draw a density, because three genes pooled into one curve
mix three different expression levels. The curve stops at the range of the x scale, so
xlim() widens the scale to show both tails. alpha makes the two filled curves see-through
where they overlap.
egfr <- expr |> filter(gene == "EGFR")
density_plot <- ggplot(egfr, aes(x = log2_cpm, fill = condition)) + geom_density(alpha = 0.5) + xlim(8, 13.5) + scale_fill_manual(values = condition_fill) + labs(x = "EGFR log2 CPM", y = "Density", fill = NULL) + theme_minimal(base_size = 13)
ggsave( "outputs/ggplot2-density.png", density_plot, width = 6, height = 4, dpi = 150, bg = "white")
Bar plot of counts
Section titled “Bar plot of counts”Count first, then draw the counts with geom_col(). geom_bar() does the counting itself
when you give it the raw table and only an x aesthetic.
deg_counts <- degs |> count(status)deg_counts# A tibble: 3 × 2 status n <chr> <int>1 Down 592 NS 18743 Up 67bars <- ggplot(deg_counts, aes(x = status, y = n, fill = status)) + geom_col(width = 0.6) + geom_text(aes(label = n), vjust = -0.4, size = 4.5) + scale_fill_manual(values = status_colors) + scale_y_continuous(expand = expansion(mult = c(0, 0.08))) + labs(x = NULL, y = "Genes") + theme_classic(base_size = 13) + theme(legend.position = "none")
ggsave( "outputs/ggplot2-barplot.png", bars, width = 5, height = 4, dpi = 150, bg = "white")
Facets
Section titled “Facets”facet_wrap() draws one panel per gene. scales = "free_y" gives each panel its own y range,
which suits genes expressed at different levels. Use facet_grid(rows ~ cols) to split by two
variables.
facets <- ggplot(expr, aes(x = condition, y = log2_cpm, fill = condition)) + geom_boxplot(width = 0.5, outliers = FALSE) + geom_point(position = position_jitter(width = 0.1, seed = 42), size = 1) + scale_fill_manual(values = condition_fill) + facet_wrap(~gene, scales = "free_y") + labs(x = NULL, y = "log2 CPM") + theme_bw(base_size = 13) + theme(legend.position = "none")
ggsave( "outputs/ggplot2-facets.png", facets, width = 7, height = 3.5, dpi = 150, bg = "white")
Means and error bars
Section titled “Means and error bars”stat_summary() computes a summary per x value from the raw replicates, so you do not need
a separate summary table. mean_se returns the mean with one standard error on each side.
time_course <- expand_grid( treatment = c("Control", "Drug A"), day = c(0, 1, 2, 4, 7), replicate = 1:3) |> mutate( log2_cpm = 6 + if_else(treatment == "Drug A", 0.4 * day, 0) + rnorm(n(), 0, 0.3) )
time_plot <- ggplot( time_course, aes(x = day, y = log2_cpm, color = treatment)) + geom_point(alpha = 0.4, position = position_jitter(width = 0.1, seed = 42)) + stat_summary(fun = mean, geom = "line", linewidth = 1) + stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.25) + scale_color_manual(values = c(Control = "#4DBBD5", `Drug A` = "#E64B35")) + scale_x_continuous(breaks = c(0, 1, 2, 4, 7)) + labs(x = "Day", y = "log2 CPM", color = NULL) + theme_minimal(base_size = 13)
ggsave( "outputs/ggplot2-time-course.png", time_plot, width = 6, height = 4, dpi = 150, bg = "white")
Lines take their width from linewidth. Since ggplot2 3.4.0, size on a line still works
but prints a deprecation warning.
Error bars from a summary table
Section titled “Error bars from a summary table”When the means and standard deviations are already in a table, map them directly.
geom_errorbar() needs ymin and ymax, and the points and bars share one dodge width.
expr_summary <- expr |> group_by(gene, condition) |> summarise(mean = mean(log2_cpm), sd = sd(log2_cpm), .groups = "drop")expr_summary# A tibble: 6 × 4 gene condition mean sd <chr> <chr> <dbl> <dbl>1 BRCA1 Control 6.94 0.4892 BRCA1 Treated 6.51 0.5003 EGFR Control 10.1 0.6874 EGFR Treated 11.6 0.3975 TP53 Control 8.91 0.5656 TP53 Treated 8.92 0.626dodge <- position_dodge(width = 0.5)
errorbars <- ggplot( expr_summary, aes(x = gene, y = mean, color = condition)) + geom_point(size = 3, position = dodge) + geom_errorbar( aes(ymin = mean - sd, ymax = mean + sd), width = 0.2, position = dodge ) + scale_color_manual(values = condition_fill) + labs(x = NULL, y = "log2 CPM, mean and SD", color = NULL) + theme_classic(base_size = 13)
ggsave( "outputs/ggplot2-errorbars.png", errorbars, width = 6, height = 4, dpi = 150, bg = "white")
Trend line with a confidence band
Section titled “Trend line with a confidence band”geom_smooth(method = "lm") fits a straight line and shades its 95% confidence band. Pass
formula = y ~ x to silence the message about the formula, and se = FALSE to drop the band.
coexpression <- tibble( myc = rnorm(40, mean = 8, sd = 1)) |> mutate(cdk4 = 2 + 0.7 * myc + rnorm(40, mean = 0, sd = 0.5))
trend <- ggplot(coexpression, aes(x = myc, y = cdk4)) + geom_point(size = 2, alpha = 0.7) + geom_smooth(method = "lm", formula = y ~ x, color = "#DC0000") + labs(x = "MYC, log2 CPM", y = "CDK4, log2 CPM") + theme_minimal(base_size = 13)
ggsave( "outputs/ggplot2-smooth.png", trend, width = 5.5, height = 4.5, dpi = 150, bg = "white")
Small heatmap with geom_tile
Section titled “Small heatmap with geom_tile”geom_tile() draws one cell per row of a long table. scale_fill_gradient2() centers a
diverging scale on midpoint, so zero stays white, and symmetric limits give the two
colors the same reach. For a clustered heatmap, use the
ComplexHeatmap cheatsheet instead.
up_genes <- paste0("GENE", 1:4)treated_samples <- c("S4", "S5", "S6")
tile_data <- expand_grid( gene = paste0("GENE", 1:8), sample = paste0("S", 1:6)) |> mutate( shift = if_else(gene %in% up_genes & sample %in% treated_samples, 1.5, 0), z = rnorm(n(), mean = shift, sd = 0.6) )
tiles <- ggplot(tile_data, aes(x = sample, y = gene, fill = z)) + geom_tile(color = "white") + scale_fill_gradient2( low = "#2166AC", mid = "white", high = "#B2182B", midpoint = 0, limits = c(-3, 3) ) + labs(x = NULL, y = NULL, fill = "z-score") + theme_minimal(base_size = 13) + theme(panel.grid = element_blank())
ggsave( "outputs/ggplot2-tiles.png", tiles, width = 5, height = 4.5, dpi = 150, bg = "white")
Enrichment dot plot
Section titled “Enrichment dot plot”The usual way to show over-representation results puts the terms on y, ordered by a value,
the gene ratio on x, the gene count as size, and the adjusted p-value as color.
reorder() sets the term order before the plot is drawn, and the log10 color scale puts red
on the smallest p-values. The results below are simulated.
The terminology examples credit the Gene Ontology Consortium under CC BY 4.0. The lesson selects or shortens labels for demonstration. The counts, set sizes and p-values in this figure are simulated.
enrichment <- tibble( term = c( "response to glucocorticoid", "inflammatory response", "extracellular matrix organization", "regulation of cell migration", "angiogenesis", "response to hypoxia", "circadian rhythm", "lipid metabolic process" ), count = c(18, 25, 30, 22, 15, 12, 9, 14), set_size = c(120, 410, 290, 380, 210, 230, 140, 520), padj = c(1e-8, 3e-6, 2e-5, 4e-4, 2e-3, 8e-3, 1e-2, 4e-2)) |> mutate(gene_ratio = count / set_size)
dots <- ggplot( enrichment, aes(x = gene_ratio, y = reorder(term, gene_ratio), size = count, color = padj)) + geom_point() + scale_color_gradient( low = "#DC0000", high = "#3C5488", transform = "log10" ) + scale_size_area(max_size = 8) + labs(x = "Gene ratio", y = NULL, size = "Genes", color = "Adjusted p") + theme_bw(base_size = 12)
ggsave( "outputs/ggplot2-enrichment-dots.png", dots, width = 7.5, height = 4.5, dpi = 150, bg = "white")
Combine plots with patchwork
Section titled “Combine plots with patchwork”patchwork joins ggplot objects with + and /. plot_annotation(tag_levels = "A") adds the
panel letters a figure legend refers to.
library(patchwork)
combined <- (volcano + theme(legend.position = "none")) + ma_plot + plot_annotation(tag_levels = "A")
ggsave( "outputs/ggplot2-patchwork.png", combined, width = 10, height = 4.5, dpi = 150, bg = "white")
Built-in themes
Section titled “Built-in themes”A complete theme sets every non-data element at once. Pick the closest one, then change single
elements with theme().
base_plot <- ggplot(expr, aes(x = gene, y = log2_cpm)) + geom_boxplot(outliers = FALSE) + labs(x = NULL, y = "log2 CPM")
themes_grid <- (base_plot + theme_grey() + ggtitle("theme_grey()")) + (base_plot + theme_minimal() + ggtitle("theme_minimal()")) + (base_plot + theme_classic() + ggtitle("theme_classic()")) + (base_plot + theme_bw() + ggtitle("theme_bw()")) + plot_layout(ncol = 2)
ggsave( "outputs/ggplot2-themes.png", themes_grid, width = 8, height = 6, dpi = 150, bg = "white")
Change single theme elements
Section titled “Change single theme elements”element_text(), element_line(), and element_blank() replace one element and keep the
rest of the theme.
tweaked <- box + labs(title = "Expression by condition") + theme( plot.title = element_text(face = "bold"), axis.text.x = element_text(angle = 45, hjust = 1, face = "italic"), panel.grid.major.y = element_line(color = "grey90"), legend.position = "bottom" )
ggsave( "outputs/ggplot2-theme-tweaks.png", tweaked, width = 6, height = 4.5, dpi = 150, bg = "white")
Map a column named in a string
Section titled “Map a column named in a string”Inside a function or a loop, the column name is often a string. Use the .data pronoun.
Older tutorials use aes_string(), which has been deprecated since ggplot2 3.0.0 and now
prints a warning.
y_column <- "log2fc"string_plot <- ggplot(degs, aes(x = base_mean, y = .data[[y_column]])) + geom_point(size = 0.5) + scale_x_log10()Save a figure
Section titled “Save a figure”ggsave() takes the size in inches by default. Use PNG at 150 to 300 dpi for slides and the
web, and PDF for a journal, because PDF keeps text and points as vectors. Set bg = "white",
otherwise some themes save with a transparent background.
ggsave( "outputs/ggplot2-volcano.pdf", volcano, width = 6, height = 4.5, bg = "white")See also
Section titled “See also”- Publication-Ready Figures draws each figure type in R and Python with the test built in.
- Raincloud Plot combines a half violin, a box, and the points.
- RNA-seq Visualization draws the volcano plot and heatmap from a real DESeq2 result.
- Tidyverse Essentials covers the dplyr and tidyr steps that prepare a table for plotting.
- The ggpubr cheatsheet adds test results to these plots.
Scientific references
Section titled “Scientific references”Wickham, 2016, describes the package in ggplot2: Elegant Graphics for Data Analysis, the citation that ggplot2 gives.
Further reading
Section titled “Further reading”-
The reference explains theme inheritance and the axis, legend and panel settings used in these figures.