Matplotlib (Condensed Reference)
Complete learning notes
1. Introduction
Module 1, Topic 7 covered Matplotlib's core chart types — line, bar, scatter, and histogram. This condensed reference topic covers the practical layout and presentation tools that turn individual charts into polished, multi-panel figures: subplots, figure sizing, and saving output — skills you'll want whenever a single chart isn't enough to tell the whole story.
2. What New Capabilities Does This Topic Add?
Simple definition: Beyond single charts, Matplotlib lets you arrange multiple plots side by side in one figure, control the overall figure's size and style, and save finished charts as image files for reports or presentations.
Technical explanation: plt.subplots() creates a figure containing a grid of individual axes (each capable of holding its own chart), figsize controls the overall figure dimensions, and plt.savefig() exports the rendered figure to an image file — together enabling the creation of comprehensive, multi-panel visual summaries rather than isolated single charts.
3. Why is it Important?
- Real-world data exploration often requires comparing several charts side by side (e.g., a model's training curve AND its confusion matrix, shown together).
- Well-formatted, appropriately sized figures are essential for reports, presentations, and publications.
plt.savefig()is how you actually deliver a chart as a file, rather than just viewing it once in a notebook.
4. Prerequisites
Full comfort with Matplotlib Basics (Module 1, Topic 7) is assumed.
5. Core Concepts
plt.subplots()— multiple charts in one figurefigsize— controlling figure dimensions- Titles, shared axes, and layout adjustment
plt.savefig()— exporting figures as image files
6. Detailed Explanation
a) `plt.subplots()`
fig, axes = plt.subplots(rows, cols) creates a figure containing a grid of individual "axes" (subplot slots) arranged in the specified number of rows and columns. Each individual axes object can then be plotted on independently (e.g., axes[0].plot(...), axes[1].bar(...)), allowing multiple different charts to appear together in one unified figure.
b) `figsize`
The figsize=(width, height) parameter (in inches) controls the overall size of the figure — important for ensuring charts are readable and appropriately proportioned, especially when combining multiple subplots.
c) Titles, Shared Axes, and Layout
Each subplot can have its own title (axes[i].set_title(...)) in addition to an overall figure title (fig.suptitle(...)). plt.tight_layout() automatically adjusts spacing between subplots to prevent titles/labels from overlapping.
d) `plt.savefig()`
plt.savefig("filename.png", dpi=300) exports the current figure to an image file, with dpi (dots per inch) controlling output resolution/quality — essential for including charts in reports, presentations, or published documents rather than only viewing them once interactively.
7. How It Works
- Create a figure and grid of subplot axes:
fig, axes = plt.subplots(rows, cols, figsize=(width, height)). - Plot on each individual axes object separately.
- Add titles and adjust layout (
plt.tight_layout()) to keep everything readable. - Either display with
plt.show()or export withplt.savefig(...).
8. Real-World Example
A data scientist presenting model results might create a single figure with 4 subplots: a confusion matrix heatmap (top-left), an ROC curve (top-right), a feature importance bar chart (bottom-left), and a residual plot (bottom-right) — combining Module 6's evaluation visuals into one comprehensive, presentation-ready summary image, saved as a single high-resolution file for a report.
9. Python Example
pythonimport matplotlib.pyplot as plt import numpy as np months = ["Jan", "Feb", "Mar", "Apr"] sales = [200, 250, 220, 300] subjects = ["Math", "Science", "English"] scores = [85, 78, 92] # Creating a figure with 2 subplots side by side fig, axes = plt.subplots(1, 2, figsize=(10, 4)) axes[0].plot(months, sales, marker="o", color="blue") axes[0].set_title("Monthly Sales") axes[0].set_xlabel("Month") axes[0].set_ylabel("Sales") axes[1].bar(subjects, scores, color="orange") axes[1].set_title("Subject Scores") axes[1].set_xlabel("Subject") axes[1].set_ylabel("Score") fig.suptitle("Business Dashboard Overview") plt.tight_layout() plt.savefig("dashboard_overview.png", dpi=150) plt.show()
Expected Output:
text(A single figure window showing two charts side by side: a sales line chart on the left, and a subject scores bar chart on the right, both under a shared title "Business Dashboard Overview" — also saved as "dashboard_overview.png")
10. Code Explanation
plt.subplots(1, 2, figsize=(10, 4))creates one row of two subplot slots, in a figure 10 inches wide and 4 inches tall.axes[0]andaxes[1]refer to the left and right subplot slots respectively — each can be plotted on and labeled completely independently.fig.suptitle(...)adds one overall title spanning the entire figure, distinct from each subplot's individual title.plt.tight_layout()automatically adjusts spacing so titles and labels don't overlap between the two subplots.plt.savefig("dashboard_overview.png", dpi=150)exports the entire combined figure as a single image file, ready for inclusion in a report or presentation.
11. Advantages
- Enables comprehensive, multi-panel visual summaries rather than isolated single charts.
figsizeanddpigive precise control over output quality and proportions for professional presentation.plt.savefig()allows charts to be delivered as standalone files, not just viewed once interactively.
12. Limitations
- Arranging many subplots can become visually cluttered if not carefully planned.
- Manually coordinating shared titles/labels across many subplots requires some extra code and attention.
- Very high
dpivalues increase file size, which may not always be necessary depending on the use case.
13. Common Mistakes
- Forgetting
plt.tight_layout(), resulting in overlapping titles/labels between subplots. - Confusing a subplot's individual title (
axes[i].set_title()) with the figure's overall title (fig.suptitle()). - Calling
plt.savefig()AFTERplt.show()— in some environments, this can save a blank figure, sinceplt.show()can clear the current figure;savefig()should generally be called beforeshow().
14. Best Practices
- Use
plt.subplots()when comparing multiple related charts together tells a more complete story. - Always call
plt.tight_layout()when using multiple subplots, to avoid overlapping elements. - Choose
figsizeanddpiappropriately for the final destination (screen viewing vs print-quality report). - Call
plt.savefig()beforeplt.show()to reliably save the intended figure.
15. Real-World Applications
- Creating comprehensive model evaluation dashboards (confusion matrix + ROC curve + feature importance, side by side).
- Producing publication-quality figures for reports, papers, or presentations.
- Comparing multiple related trends or categories in one unified visual summary.
16. Interview-Oriented Points
- Be ready to explain how
plt.subplots()creates a grid of independent axes within one figure. - Understand the difference between a subplot's individual title and the figure's overall title.
- Be able to explain what
dpicontrols when saving a figure.
17. Exam-Oriented Points
plt.subplots(rows, cols)creates a grid of subplot axes within one figure.figsizecontrols overall figure dimensions;dpicontrols saved image resolution.plt.savefig()exports the current figure as an image file;plt.tight_layout()prevents overlapping elements.
18. Comparison Table — Single Plot vs Subplots
| Aspect | Single Plot (plt.plot(), etc.) | Subplots (plt.subplots()) |
|---|---|---|
| Number of charts per figure | One | Multiple, arranged in a grid |
| Best suited for | A single, focused visualization | Comparing multiple related charts together |
| Layout control | Not applicable | Requires figsize, tight_layout() for clean presentation |
| Example use case | A single sales trend line | A full evaluation dashboard with 4 different charts |
19. Quick Revision
plt.subplots(rows, cols, figsize=(...))creates a grid of independent subplot axes within one figure.- Each subplot can have its own title;
fig.suptitle()adds an overall figure title. plt.tight_layout()prevents overlapping elements between subplots.plt.savefig("file.png", dpi=...)exports the figure as an image file — call it beforeplt.show().