LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 25 lessons

Lesson 5 of 5

Module 1 · R basics

Figures with ggplot2

Figures with ggplot2

Figures with ggplot2

ggplot2 builds a figure in layers: data, how columns map to what you see, and the shapes that draw them. Learn the pattern once and every plot type follows, including heatmaps.

⏱ 14 min readModule 1 · R basicsFree
Lesson at a glance3 steps · about 14 min
  1. The grammar
  2. Heatmaps with pheatmap
  3. Saving figures

The grammar

  1. Data: a data frame, usually in long format.
  2. Aesthetics, aes(): which column goes on x, on y, and sets the colour.
  3. Geoms: the shapes. geom_point(), geom_boxplot(), geom_violin(), geom_histogram(). Layers are added with +.

The "gg" in ggplot2 stands for the grammar of graphics, the idea that any chart can be described by the same few parts. An aesthetic is any visual property a value can control: position on the x- or y-axis, colour, fill, size or shape. A geom, short for geometric object, is the kind of mark that draws the data: a point, a box, a bar, a line. Because the parts are separate, you can keep the data and aesthetics and swap one geom for another, and the rest of the code stays the same.

This is also why ggplot2 wants long data (Cleaning data with dplyr and tidyr). An aesthetic maps one column to one visual property. If the groups are in one column, called condition, that column can set both the x position and the fill colour. If each group were its own column, there would be no single column to map.

Beyond the three core parts, every ggplot can take further layers, each added with +: scales control how values become colours or axis positions, labs() sets titles, themes set the look of text and background, and facets split one plot into small panels, one per group, with facet_wrap(~ condition). You will see most of them in the code below. Each layer changes one thing, so you can build a figure a line at a time and look at it after each step.

One detail of the syntax trips up almost everyone at first. The + must come at the end of a line, not the start of the next one. R reads a line ending in + as unfinished and waits for more, the + prompt from Setting up R and RStudio. A line that starts with + comes after a command R has already treated as complete, so it fails with an error.

Here we simulate expression values for 200 genes in two groups. set.seed() makes the random numbers repeatable.

Computers generate random numbers with a fixed recipe that starts from a number called the seed. The same seed always gives the same sequence, so anyone running this code gets exactly the same 400 values, and exactly the same figure. Without set.seed() the numbers, and the plot, would differ slightly every time.

R
library(ggplot2)

set.seed(1)
expr <- data.frame(
  condition = rep(c("normal", "tumour"), each = 200),
  log_expr  = c(rnorm(200, mean = 6, sd = 2), rnorm(200, mean = 6.5, sd = 2))
)

ggplot(expr, aes(x = condition, y = log_expr, fill = condition)) +
  geom_violin(alpha = 0.4, colour = NA) +
  geom_boxplot(width = 0.15, outlier.shape = NA) +
  scale_fill_manual(values = c(normal = "#0F1B33", tumour = "#D9481F")) +
  labs(x = NULL, y = "log2 expression") +
  theme_minimal(base_size = 13) +
  theme(legend.position = "none")

What this does, line by line

  1. library(ggplot2) loads the package, and set.seed(1) fixes the random numbers.
  2. rep(c("normal", "tumour"), each = 200) repeats each label 200 times: 200 copies of "normal" followed by 200 of "tumour".
  3. rnorm(200, mean = 6, sd = 2) draws 200 random values from a normal distribution (the bell-shaped curve) with mean 6 and standard deviation 2. The tumour group is drawn the same way with mean 6.5. c() joins the two sets of 200 into one column of 400 values, in the same order as the labels.
  4. data.frame(…) puts the two columns together: 400 rows, one per simulated gene measurement.
  5. ggplot(expr, aes(x = condition, y = log_expr, fill = condition)) names the data and the mappings: groups on x, values on y, fill colour by group. On its own this draws only empty axes.
  6. geom_violin(alpha = 0.4, colour = NA) adds a violin for each group. alpha sets transparency from 0 (invisible) to 1 (solid); colour = NA removes the outline.
  7. geom_boxplot(width = 0.15, outlier.shape = NA) draws a narrow box on top. outlier.shape = NA hides the separate outlier dots, because the violin already shows those values.
  8. scale_fill_manual(values = c(normal = "#0F1B33", tumour = "#D9481F")) sets the fill colours by name, so "normal" is always navy and "tumour" always vermilion, whatever order the groups appear in.
  9. labs(x = NULL, y = "log2 expression") removes the x-axis title (the group names are enough) and labels the y-axis.
  10. theme_minimal(base_size = 13) uses a clean theme with 13-point text, and theme(legend.position = "none") hides the legend, which would only repeat the x-axis labels.

Notice the difference between a mapped and a fixed aesthetic. Inside aes(), fill = condition means "let the column decide the colour", so each group gets its own. Outside aes(), colour = NA and alpha = 0.4 are fixed settings that apply to every violin. A common slip is to write aes(fill = "navy"): ggplot2 treats "navy" as a one-value column, colours everything with its first default colour, which is not navy, and adds a legend entry labelled "navy". To set one colour for everything, put it outside aes().

The groups appear in alphabetical order, normal then tumour, which here happens to be the order you want. When it is not, set the order with a factor, as in Data frames and files: factor(expr$condition, levels = c("normal", "tumour")) fixes the order on the axis and in any legend.

The violin shows the whole distribution; the box inside shows the median and middle half. Together they say more than a bar chart of means. Swap in geom_histogram() with aes(x = log_expr) to see one distribution, or geom_point() for two numeric columns.

How to read a box plot: the box runs from the first quartile (the value below which a quarter of the data lie) to the third quartile (below which three quarters lie), so it holds the middle half of the values. The line across it is the median. In ggplot2 the whiskers reach to the most extreme values that lie within 1.5 times the box height of the box; anything beyond would normally be drawn as a separate outlier dot. The violin's width at each height shows how many values lie there, as a smoothed outline mirrored on both sides.

In this simulation the true means differ by only 0.5, a quarter of the standard deviation of 2, so the two violins overlap heavily. A bar chart of the two means would show two bars of slightly different height and hide that overlap entirely. The sample means will also not be exactly 6 and 6.5, because 200 random values never match their source perfectly.

A histogram gives a second view of the same data. ggplot(expr, aes(x = log_expr, fill = condition)) + geom_histogram(bins = 30, alpha = 0.5, position = "identity") splits the range of values into 30 bins and draws a bar for how many values fall in each, one colour per group. position = "identity" draws the two groups on top of each other, with transparency so both stay visible; without it ggplot2 stacks them. The number of bins changes the picture: too few hide the shape, too many make it look jagged, so try two or three values before choosing.

Figures with ggplot2 · LSMA free course A long data frame with condition and log_expr columns; aesthetics mapping condition to x and fill and log_expr to y; two geoms, a violin and a box plot, added with a plus sign; and the resulting plot with a navy normal violin and a vermilion tumour violin. THE GRAMMAR, PART BY PART 1 · DATA 2 · AES() 3 · GEOMS 4 · PLOT condition log_expr normal normal tumour tumour … 400 rows x = condition y = log_expr fill = condition geom_violin() + geom_boxplot() normal tumour columns to visual roles added with + long format
Each part of the code has one job: the data frame supplies the values, aes() says which column controls which visual property, and each geom adds one layer of marks. The plot in panel 4 is a sketch of the shape, not the real output. Schematic, not to scale.

The second illustration below shows another common form, bars with error bars. Whenever you meet error bars, look for what they show: the standard deviation, the standard error or a confidence interval. They answer different questions and can differ in length several times over, as A reproducible workflow explains.

051015Normalised expressionGene AGene BGene CGene DGene EGene FNormalTumour
A grouped comparison with error bars, in the same palette. Illustrative data.

The grammar of graphics comes from Leland Wilkinson's book The Grammar of Graphics (Springer, 2nd edition 2005). Hadley Wickham built ggplot2 on it, and described the design in "A layered grammar of graphics" (Journal of Computational and Graphical Statistics, 2010) and in the book ggplot2: Elegant Graphics for Data Analysis (Springer, 2016). Cite the package with citation("ggplot2") and report its version. That matters because defaults and argument names change between major releases; version 4.0, released in 2025, was a large update, so code and figures from older versions can look slightly different.

Heatmaps with pheatmap

For a grid of genes by samples, the pheatmap package draws a clustered heatmap in one line. scale = "row" shows each gene relative to its own average, which is what you usually want.

A heatmap shows a table of numbers as a grid of coloured cells, one row per gene and one column per sample. "Clustered" means the rows and columns are reordered so that similar ones sit next to each other, and tree diagrams called dendrograms along the edges show which joined first. By default pheatmap uses hierarchical clustering with Euclidean distance.

Row scaling matters because genes differ enormously in their average level: a housekeeping gene such as GAPDH may have thousands of times more reads than a transcription factor. Without scaling, the colour would mostly show which genes are abundant, not how each gene changes between samples. With scale = "row", each value is turned into a z-score: the row's mean is subtracted and the result divided by the row's standard deviation, so every gene is centred on 0 and a value of +1 means "one standard deviation above this gene's own average".

R
library(pheatmap)

mat <- matrix(rnorm(60), nrow = 10,
              dimnames = list(paste0("Gene", 1:10), paste0("S", 1:6)))
pheatmap(mat, scale = "row")

What this does

  • library(pheatmap) loads pheatmap, which you installed with the run-once line in Setting up R and RStudio. If R says there is no package called pheatmap, run install.packages("pheatmap") once.
  • rnorm(60) draws 60 random values from a standard normal distribution (mean 0, standard deviation 1).
  • matrix(…, nrow = 10, dimnames = …) arranges them as 10 rows and 6 columns. paste0("Gene", 1:10) glues "Gene" to the numbers 1 to 10, giving Gene1 to Gene10; paste0("S", 1:6) gives S1 to S6.
  • pheatmap(mat, scale = "row") scales each row, clusters rows and columns, and draws the heatmap with its dendrograms and a colour key.

Note that this code does not call set.seed(), so your random matrix, and your heatmap, will differ from anyone else's. Because the values are pure noise, any clusters you see are chance. Clustering always produces a tree, even from random numbers; a neat-looking dendrogram is not by itself evidence of real groups.

With real RNA-seq data, plot transformed values, such as log2 counts, not raw counts. On raw counts a handful of very large values dominate the colour range. Remove genes whose values are the same in every sample before scaling: a constant row has a standard deviation of zero, the z-score divides by zero, and pheatmap stops with an error about NA, NaN or Inf values. Genes that never change carry no information for the heatmap anyway.

Two more arguments are worth knowing. annotation_col takes a data frame with one row per sample, its row names matching the column names of the matrix, and draws a coloured strip above the heatmap, for example to mark treated and untreated samples. You can then see at a glance whether the columns cluster by treatment, by donor or by neither. cluster_cols = FALSE keeps the samples in the order you gave, which is useful when that order means something, such as a time course.

Gene 1Gene 2Gene 3Gene 4Gene 5Gene 6Gene 7Gene 8Gene 9Gene 10Gene 11Gene 12+2−2NormalTumour
A clustered heatmap: rows and columns are reordered so similar ones sit together. Illustrative data.

Saving figures

R
ggsave("violin.png", width = 6, height = 4, dpi = 300)        # last ggplot
pheatmap(mat, scale = "row", filename = "heatmap.png")          # pheatmap saves itself

What this does

  • ggsave("violin.png", width = 6, height = 4, dpi = 300) saves the most recent ggplot. Width and height are in inches by default, and dpi is dots per inch, so the image is 6 × 300 = 1,800 pixels wide and 4 × 300 = 1,200 pixels high. 300 dpi is a common requirement for journal figures.
  • pheatmap does not work with ggsave(); instead you give it a filename, and it writes the file instead of drawing on screen.

Both functions choose the file type from the ending of the name. A .png file is a grid of pixels and becomes blurry if enlarged; a .pdf or .svg file stores shapes and stays sharp at any size, which is often better for posters and papers. Save figures from code rather than with the Export button, so the exact size and resolution are recorded in your script.

Journals usually give figure widths in millimetres, often one size for a single column and a larger one for a full page width; check the author guidelines for the exact numbers. ggsave() accepts units = "mm" or units = "cm", so you can enter the journal's width directly. pheatmap takes width and height arguments too, in inches, alongside filename.

Size changes how a figure looks, not only how large it is. Text size in ggplot2 is set in points, a physical unit, so the same plot saved at 6 inches wide and at 12 inches wide has text of the same physical size, which looks much smaller relative to the plot in the wider file. Choose the final size first and adjust base_size to suit it, rather than saving a large image and shrinking it later, which shrinks the text with it.

Keep figures in their own folder, such as figures inside the project. ggsave("figures/violin.png", width = 6, height = 4, dpi = 300) stops with an error if the folder does not exist yet; create it once with dir.create("figures"). Because the path is relative to the project, the script still works when the folder is copied to another computer.

Go deeper: a ggplot is an object, not a drawing

ggplot() does not draw anything when it runs. It builds an object that describes the plot, and R draws it only when that object is printed. At the console, printing happens automatically, so the two steps look like one. Store the plot instead, as in p <- ggplot(expr, aes(condition, log_expr)) + geom_boxplot(), and nothing appears until you type p.

This explains two common puzzles. Inside a for loop or a function, automatic printing is switched off, so a plot made there never appears; wrap it in print(p). And because p is an object, you can add layers later, as in p + geom_point(), or save it by name with ggsave("box.png", p) rather than relying on the last plot drawn. Naming each figure makes a script easier to rerun and to check.

Key point

Use one colour per group and keep it the same in every figure: here, navy for the reference group and vermilion for the comparison. Readers learn the code once.

The same goes for order. If "normal" is on the left in your first figure, keep it on the left in all of them. Also avoid using red against green as the only difference between groups, because red–green colour blindness is common, especially in men; colours that also differ in lightness, such as navy and vermilion, stay distinguishable.

That completes Module 1. You can now install packages, store values and write small functions, read a sample sheet and check it, clean a messy table and reshape it, and draw and save a figure. Module 2, Statistics, builds directly on each of those steps. It opens with Describing data, which reads a real dataset of births, turns its numeric codes into labelled factors, and summarises it by group with the dplyr verbs from Cleaning data with dplyr and tidyr. The figures from this lesson then come back as the first check before every test: look at the distributions before you compare them.

End of Module 1: R basicsYou can stop here: this module is complete on its own. Or carry on to Module 2, Statistics (Intermediate).

Further reading · Module 1R for Data Science, 2nd edition: the free book that covers this module and much more. · All reading for this course

Check your understanding

1. What does aes() define?

2. Why use a violin with a box, rather than a bar of means?

3. What does scale = "row" do in pheatmap?

Up next

Lesson 1

Describing data

Ask BioTutor

Create a free website with Framer, the website builder loved by startups, designers and agencies.