Skip to content

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().

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 <- 2000
n_de <- 150
degs <- 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 NS
2 GENE0002 19044. 0.157 0.264 0.552 1.000 NS
3 GENE0003 100. 0.291 0.450 0.517 1.000 NS
# ℹ 1,997 more rows

The 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.59
2 TP53 Control_2 Control 8.52
3 TP53 Control_3 Control 8.76
# ℹ 69 more rows

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"
)

Volcano plot of 2,000 simulated genes. Grey non-significant genes sit in a cloud near zero, 59 blue down-regulated genes rise to the left and 67 red up-regulated genes rise to the right, reaching about 45 on the -log10 adjusted p-value axis. Dashed lines mark log2 fold changes of -1 and 1 and an adjusted p-value of 0.05.

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"
)

The same volcano plot with the eight most significant genes labelled. GENE1987, GENE1863 and GENE1939 are labelled on the left, GENE1933, GENE1859, GENE1977, GENE1947 and GENE1926 on the right, each joined to its point by a short line.

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"
)

MA plot with mean count on a log10 axis from 10 to 30,000 and log2 fold change from -4 to 4. Most genes sit in a pale band around zero. Points away from zero are colored from orange to black by -log10 adjusted p-value, capped at 20, and the darkest points have mean counts above 200.

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"
)

Boxplots of log2 CPM for BRCA1, EGFR and TP53, with a blue control box and a red treated box per gene and the 12 samples drawn over each box. EGFR rises from a median near 10 in control to about 11.6 in treated, BRCA1 falls from about 6.9 to 6.5, and TP53 stays near 8.8.

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"
)

Violin plots of log2 CPM for BRCA1, EGFR and TP53 by condition, each with a narrow boxplot inside. The treated EGFR violin sits above the control violin and is narrower, centered near 11.6.

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"
)

Histogram of log2 fold changes with 0.2-wide bins. A tall peak of nearly 500 genes sits at zero, marked by a red dashed line, and small groups of differentially expressed genes spread out to -4 and 4.

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"
)

Overlaid density curves of EGFR log2 CPM. The blue control curve peaks near 9.8 and the red treated curve peaks higher and sharper near 11.7, with a small overlap around 11.

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 59
2 NS 1874
3 Up 67
bars <- 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"
)

Bar chart of gene counts by status, labelled 59 for Down in blue, 1874 for NS in grey and 67 for Up in red.

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"
)

Three panels, one per gene, each with a control and a treated boxplot and its own y axis range. EGFR shows the clearest increase in treated samples, BRCA1 a smaller decrease, and TP53 no change.

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"
)

Line plot of log2 CPM over days 0, 1, 2, 4 and 7, with the three replicates as faint points and the mean with standard error bars. Drug A rises from about 5.8 to 8.6 by day 7, while Control stays near 6.

Lines take their width from linewidth. Since ggplot2 3.4.0, size on a line still works but prints a deprecation warning.

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.489
2 BRCA1 Treated 6.51 0.500
3 EGFR Control 10.1 0.687
4 EGFR Treated 11.6 0.397
5 TP53 Control 8.91 0.565
6 TP53 Treated 8.92 0.626
dodge <- 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"
)

Mean log2 CPM with standard deviation error bars for BRCA1, EGFR and TP53, with control in blue and treated in red, dodged side by side. EGFR rises from a mean of 10.1 in control to 11.6 in treated, BRCA1 falls from 6.94 to 6.51, and TP53 stays at 8.9 in both.

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"
)

Scatter plot of CDK4 against MYC for 40 simulated samples, with a red least squares line rising from about 6.1 at MYC 6.1 to about 8.5 at MYC 9.3 and a grey 95% confidence band that widens at both ends.

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"
)

Tile heatmap of eight genes by six samples on a blue, white and red scale from -3 to 3. GENE1 to GENE4 are red in samples S4, S5 and S6, and the other cells are pale blue, white or pale red.

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"
)

Enrichment dot plot of eight simulated terms ordered by gene ratio, from response to glucocorticoid at the top, near 0.15, to lipid metabolic process at the bottom, near 0.03. Dot size shows the gene count from 9 to 30, and color runs from red at an adjusted p of 1e-08 to blue at 4e-02.

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"
)

Two panels side by side, tagged A and B. Panel A is the volcano plot without its legend and panel B is the MA plot with its color bar.

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"
)

The same three-gene boxplot drawn four times with theme_grey, theme_minimal, theme_classic and theme_bw. theme_grey has a grey panel with white grid lines, theme_minimal has light grid lines and no border, theme_classic has axis lines and no grid, and theme_bw has a full border with grid lines.

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"
)

The condition boxplot with a bold title, Expression by condition, gene names in italics rotated 45 degrees, light horizontal grid lines, and the legend moved below the plot.

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()

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"
)

Wickham, 2016, describes the package in ggplot2: Elegant Graphics for Data Analysis, the citation that ggplot2 gives.

  • ggplot2 theme reference

    The reference explains theme inheritance and the axis, legend and panel settings used in these figures.