Python Reference ยท Third-party Libraries
The Matplotlib library
Overview of Matplotlib: figures and axes, line, bar, scatter and histogram plots, labels, legends, subplots, saving images, and the pyplot habits that avoid bugs.
Matplotlib is Python's most widely used plotting library. You describe a chart in code (data, labels, colors) and it draws line plots, bars, scatter plots, histograms, heat maps and much more, then shows them or saves them as PNG, SVG or PDF.
Install it with python -m pip install matplotlib. Most code starts with import matplotlib.pyplot as plt. In the live examples below, figures appear as images under the editor after the code runs.
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [2, 4, 9]) plt.show()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Core ideas
Figure and Axes. A figure is the whole canvas; an axes is one plot inside it, with its own x and y axis. fig, ax = plt.subplots() gives you both, and calling methods on ax (ax.plot, ax.set_title) is the clear, recommended style.
Two interfaces. The quick pyplot style (plt.plot(...), plt.title(...)) draws on a hidden "current" axes. It is fine for short scripts but gets confusing with several subplots. The object-oriented style names every axes explicitly.
Data in, drawing out. Matplotlib accepts lists, NumPy arrays and pandas columns. Nothing is drawn until you call plt.show() or save the figure.
Most used calls
| Call | Purpose |
|---|---|
plt.subplots(nrows, ncols, figsize=(w, h)) |
Create a figure and one or more axes. |
ax.plot(x, y) |
Line plot (with marker, linestyle, color, label). |
ax.bar(names, heights) / ax.barh(...) |
Vertical or horizontal bars. |
ax.scatter(x, y, s=, c=) |
Points with optional size and color. |
ax.hist(values, bins=) |
Histogram. |
ax.set_title, set_xlabel, set_ylabel |
Text. |
ax.set_xlim, set_ylim |
Axis ranges. |
ax.legend() |
Legend built from the label= arguments. |
fig.tight_layout() |
Avoid overlapping labels. |
fig.savefig("chart.png", dpi=150) |
Write a file. |
plt.close(fig) |
Release a figure you no longer need. |
Usage notes
- Pick a backend that fits. Desktop scripts open a window with
plt.show(); servers and notebooks need a non-interactive backend such asAgg(matplotlib.use("Agg")before importing pyplot) andsavefig. - Close figures in loops. Pyplot keeps every figure open until you call
plt.close(), and creating hundreds of them leaks memory and triggers a warning. - Save before you show in scripts: after
plt.show()returns in some backends the figure is already cleared, sosavefigwould write a blank image. - Color and style: colors can be names (
"tomato"), hex strings or"C0"cycle colors.plt.style.use("ggplot")changes defaults for everything. - Order of calls inside a subplot grid:
plt.subplots(2, 2)returns a 2-D array of axes, so useaxes[row][col](oraxes.flat). With one row or column the array is 1-D, and with 1x1 you get a single axes. - Dates: pass
datetimeobjects or pandas dates and Matplotlib formats the axis; usefig.autofmt_xdate()to rotate crowded labels. - Reproducible examples: seed random data (
np.random.default_rng(seed)) so your charts do not change on every run. - Higher-level tools such as pandas'
df.plot()and seaborn call Matplotlib underneath.
Related
- NumPy, pandas,
random,statistics - Lessons: Matplotlib, NumPy