One figure, many axes
A figure can hold several axes. Each axes has its own data, title, and limits, while the figure owns the overall size and background. This is how you place related charts side by side without opening separate windows.
Python
Two axes in one figure
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
sharey=True gives both panels the same y scale. Without it, Matplotlib can choose different limits for each panel, which makes a visual comparison misleading.
Know the shape of axes
plt.subplots(1, 2) returns a one-dimensional array with two axes. plt.subplots(2, 2) returns a two-dimensional array. Always check the shape before indexing so a row does not accidentally receive the wrong chart.
Python
Flatten a grid when every panel is treated the same
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
Give labels room
Titles, tick labels, and axis labels can overlap when several axes share a figure. Layout engines adjust the axes rectangles after the artists exist. Use layout="constrained" when creating the figure, or call fig.tight_layout() near the end.
Python
Constrained layout reserves space for labels
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
Build an uneven layout
Use GridSpec when panels should not all have the same width or height. width_ratios and height_ratios control the proportions, and add_subplot places each axes into a cell.
Python
A wide main panel with two small summaries
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
- grid[:, 0] spans both rows in the left column.
- grid[0, 1] is the upper-right cell.
- grid[1, 1] is the lower-right cell.
- summary.axis("off") removes ticks and spines for a text-only panel.
A layout checklist
A good multi-panel figure has a clear reading order, shared scales where comparison depends on them, and enough space for every label. Check those three things before adding more decoration.
Python
Compare panels on one scale
Output
Press Run to execute this cell. The first run downloads Python; later runs reuse the session.
The next lesson adds the visual layer: a restrained palette, direct annotation, and style choices that survive grayscale and color-vision differences.
Practice
Make it stick
Run the tests as often as you like. Hints and the solution are available when you need them.
Exercise
Create a 1x2 figure with shared y axes and figsize (10, 4). Plot north on the left and south on the right, both with markers. Title the panels "North" and "South", label each x-axis "Week", label the left y-axis "Signups", and add the figure title "Weekly signups by region".
Your solution
ReadyResults
Run the tests to check your solution. The first run downloads Python; later runs reuse the session.
Quiz
Check your understanding
Lesson progress