8  Assembling multiple panels

Figures in papers almost always combine several panels (A, B, C …) into one. Facets (Chapter 3) “arrange plots of the same form”; here we freely place different kinds of plots.

8.1 Basic arrangement

Once you load patchwork, you can arrange ggplot figures with operators.

Syntax Meaning
p1 + p2 or p1 \| p2 Side by side
p1 / p2 Stacked vertically
(p1 \| p2) / p3 Two on top, one below

In matplotlib, plt.subplot_mosaic() is handy: you draw the layout with a grid of letters.

layout="constrained" automatically adjusts the margins so that axis labels and legends don’t overlap (smarter than tight_layout()).

WarningWhen two legends remain even with guides = "collect"

patchwork merges only legends whose title, values and key shapes are exactly the same. The “point” legend of a scatter plot and the “square” legend of a box plot or bar chart remain separate. Make the legend names (labs(fill = "Species")) and colours consistent, and remove any legend that still remains by adding show.legend = FALSE to that plot’s geom.

8.2 Changing width and height ratios

8.3 Assembling a scatter plot with marginal distributions

As promised in Chapter 2, we build ourselves the figure with densities above and to the right of the scatter plot. The key point is to share the axes so that the ticks of the scatter plot and the marginal plots line up.

patchwork arranges panels while automatically aligning their axes. theme_void() removes the axes of the marginal plots, and plot_spacer() leaves the top right empty.

"." marks a spot where “nothing is placed”, and sharex() / sharey() share the axes between the marginal plots and the scatter plot.

8.4 Inset figures

Place a zoomed-in view of part of a large figure, or a supplementary figure, inside the panel.

8.5 Secondary axes

When you want to show the same quantity in another unit as well (g and kg, °C and °F), you can use a secondary axis.

WarningDon’t plot different quantities on the left and right axes

With a figure that has axes for different quantities on the left and right (e.g. body mass and temperature), you can make two lines look “linked” as much as you like, depending on how you choose the axis ranges. Show different quantities in panels stacked vertically (sharing the x-axis). ggplot2’s sec_axis() is deliberately designed so that it can only draw a transformation of the same quantity.

ImportantChapter summary
  • In R, patchwork (+, |, /, plot_layout(), plot_annotation(tag_levels = "A"))
  • In Python, plt.subplots() / plt.subplot_mosaic(), layout="constrained", and panel labels with ax.text(..., transform=ax.transAxes)
  • For marginal-distribution figures, share the axes (automatic in patchwork, sharex/sharey in matplotlib)
  • Insets with inset_element() / ax.inset_axes(). Use secondary axes only for unit conversions of the same quantity