Python Matplotlib

Tutorial 48 of 65 · pythondeck.com Python course

matplotlib is the de-facto plotting library. The pyplot API offers a quick MATLAB-style interface; the object-oriented API gives full control over figures and axes.

Matplotlib is the reference plotting library in Python: from quick line charts in notebooks to publication-quality figures with fine control over every artist.

Understanding its object-oriented API (Figure, Axes) separates throwaway plots from reproducible visuals you can tweak programmatically.

pyplot vs OO APIplt.plot for quick sketches; fig, ax = plt.subplots() for maintainable code.

Artists — lines, patches, text; customize via setters or style dictionaries.

Layoutstight_layout, constrained_layout for multi-panel figures.

Stylesplt.style.context, rcParams for consistent brand colors.

Backends — inline in Jupyter, Agg for headless PNG/PDF export.

Extensions — seaborn builds statistical layers atop matplotlib axes.

Every plot element lives on an Axes; the Figure is the canvas. Loop over axes when faceting instead of repeated pyplot state. For interactive exploration use %matplotlib widget sparingly in CI—prefer saving static assets. Color maps: perceptually uniform maps (viridis) for continuous data; don't use jet for science communication.

Vector formats (PDF, SVG) scale in papers; raster (PNG) needs dpi set at save time (dpi=300). Annotate units and uncertainty when presenting metrics to stakeholders.

Relying on implicit pyplot state in functions called multiple times (wrong axis).

Overlapping labels without rotation or shared axes.

Using pie charts for precise comparisons (hard to read angles).

Forgetting plt.close(fig) in loops, leaking memory in servers.

Always return or save fig explicitly in library code; avoid global pyplot.

Label axes with units; add legends only when series aren't obvious.

Use colorblind-safe palettes and direct labeling where possible.

Script style with a if __name__ == '__main__' block for reproducible figures.

Save figure and axes objects in notebooks to tweak labels after the first render.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates line plot. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: Line plot
# Run in the REPL or save as a .py file and execute with python.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 200)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.legend(); plt.title("sin / cos")
plt.show()

This sample walks through bar in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: Bar
# Run in the REPL or save as a .py file and execute with python.
import matplotlib.pyplot as plt
names = ["Ada", "Grace", "Linus"]
scores = [99, 97, 85]
plt.bar(names, scores)
plt.ylabel("score"); plt.show()

Here is a hands-on illustration of subplots. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: Subplots
# Run in the REPL or save as a .py file and execute with python.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 2, figsize=(8, 3))
ax[0].plot(np.random.randn(100))
ax[1].hist(np.random.randn(1000), bins=30)
plt.show()

The program below demonstrates line plot. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# pyplot provides MATLAB-like plotting API
import matplotlib.pyplot as plt  # plotting interface
xs = [0, 1, 2, 3]  # x coordinates
ys = [0, 1, 4, 9]  # y values (squares)
plt.plot(xs, ys, marker="o")  # line + markers
plt.title("y = x^2")  # chart title
plt.xlabel("x")  # axis labels improve readability
plt.ylabel("y")  # y label
plt.grid(True, alpha=0.3)  # light grid
plt.savefig("plot.png")  # write image file
plt.close()  # free memory
print("saved plot.png")  # confirmation

This sample walks through subplots grid in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# subplots creates multiple axes in one figure
import matplotlib.pyplot as plt  # pyplot
fig, axes = plt.subplots(1, 2, figsize=(8, 3))  # 1 row, 2 cols
axes[0].bar(["A", "B"], [3, 7])  # bar chart left
axes[1].scatter([1, 2, 3], [3, 2, 5])  # scatter right
fig.tight_layout()  # reduce label overlap
fig.savefig("panels.png")  # export composite
plt.close(fig)  # cleanup
print("saved panels.png")  # done

« Python Pandas Basics All tutorials Python Requests »