Introduction to Matplotlib

By the end of this notebook you will be able to:

How to use this notebook

The big picture

What is Matplotlib?

  • The foundational plotting library for Python, and still the most widely used
  • Created in 2003 by John D. Hunter, a neuroscientist who wanted MATLAB-quality plots in Python
  • Free, open source, and built on top of NumPy
  • Makes almost any 2D chart (and basic 3D), static or animated
  • Exports to PNG, PDF, SVG, and more, at publication quality
  • Bottom line: if a Python library draws a static chart, there is a good chance Matplotlib is doing the drawing

Where Matplotlib fits in the Python ecosystem

Think of it as a foundation layer that other tools build on:

Layer Examples What it gives you
High-level, built on Matplotlib Seaborn, pandas .plot(), GeoPandas .plot() Short commands for common statistical and DataFrame plots
Matplotlib matplotlib.pyplot Full control over every element of a figure
Numerical foundation NumPy The arrays of numbers being plotted

Separate interactive-web libraries (Plotly, Bokeh, Altair) use their own drawing engines and are aimed at browser dashboards.

Why learn Matplotlib first?

  • Seaborn and pandas plots return Matplotlib objects, so customizing them requires Matplotlib
  • Understanding the foundation makes every other plotting library easier
  • Analogy: Matplotlib is the paint and brushes; Seaborn is a paint-by-numbers kit built with them

Matplotlib vs. pyplot

  • matplotlib is the whole package: dozens of modules for colors, tick formatting, animation, 3D, file output, and more
  • matplotlib.pyplot is the one module you use day to day
    • A collection of MATLAB-style functions: plt.plot(), plt.subplots(), plt.savefig(), …
    • Keeps track of the “current” figure and plot for you behind the scenes
    • Your starting point for creating every figure
  • That is why every notebook begins with:
import matplotlib.pyplot as plt
  • You rarely import other parts of the package directly; pyplot and the objects it creates cover nearly everything in this course

How Matplotlib works under the hood

Three layers, from what you type to what you see:

  1. Scripting layer (pyplot): the simple commands you write, e.g. plt.subplots()
  2. Artist layer: everything visible on a plot is a Python object called an Artist
    • The Figure, each Axes, every line, tick, label, and legend
    • Customizing a plot = changing properties of these objects
  3. Backend layer: turns the Artists into actual pixels or files
    • In Jupyter, an inline backend draws the figure under your cell
    • When saving, a file backend writes PNG, PDF, SVG, …
    • You almost never touch this layer directly

Takeaway: you write pyplot commands, they create and modify Artist objects, and the backend draws them.

Strengths and limitations

Strengths Limitations
Total control over every detail More code than higher-level libraries
Publication-quality static output Default styling needs tuning to look professional
Works everywhere: notebooks, scripts, servers Interactivity is limited compared to web libraries
Huge gallery of examples; mature and stable Two coding styles (Section 3) confuse beginners

Use Matplotlib when you need a precise, polished figure for a report, paper, or slide deck, or when you need to fine-tune a plot made by Seaborn or pandas.

0. Setup

Install (only once, from the terminal, inside your conda environment):

conda install matplotlib numpy
# or
python -m pip install matplotlib numpy

Import (every notebook). These aliases are universal conventions, so always use them:

  • matplotlib.pyplot as plt: the plotting interface
  • numpy as np: fast arrays of numbers, used here to generate data
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

print("Matplotlib version:", matplotlib.__version__)

# Random number generator with a fixed seed, so everyone gets the same "random" data
rng = np.random.default_rng(seed=42)
Matplotlib version: 3.10.8

Two NumPy functions you will see constantly in this notebook:

  • np.linspace(start, stop, n): n evenly spaced numbers from start to stop (great for smooth curves)
  • rng.normal(mean, std, n): n random numbers from a bell curve (great for fake “measured” data)
print(np.linspace(0, 1, 5))
print(rng.normal(0, 1, 3))
[0.   0.25 0.5  0.75 1.  ]
[ 0.30471708 -1.03998411  0.7504512 ]

1. Your first plot

Three lines of code: give Matplotlib some x values, some y values, and ask it to draw.

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

plt.plot(x, y)
plt.show()

What just happened?

  • plt.plot(x, y) connected the points (1,1), (2,4), ..., (5,25) with straight lines
  • plt.show() rendered the figure
    • In Jupyter, the plot appears automatically at the end of a cell, so plt.show() is optional (but it hides extra text output, so it is a good habit)
    • In a regular .py script, plt.show() is required or nothing appears
  • Inputs can be Python lists, NumPy arrays, or pandas DataFrame columns; x and y just need the same length

2. Anatomy of a plot: Figure vs. Axes

Every Matplotlib plot is built from two main objects:

  • Figure: the whole canvas (the sheet of paper). Controls overall size, the overall title, and saving to file.
  • Axes: one individual plot inside the figure (one drawing on the paper). Holds the data, the axis labels, the title, the legend, the ticks.
    • A Figure can hold one or many Axes
    • Almost all plotting commands are methods of an Axes: ax.plot(), ax.set_xlabel(), ax.legend()

figure-vs-axes.png

Watch the spelling:

  • Axes = one whole plot panel (singular and plural are both “Axes”)
  • Axis = a single number line (the x-axis or the y-axis) inside an Axes

The labeled figure below names every component and the command that controls it. Keep it as a reference.

anatomy.png

3. Two ways to write Matplotlib code

You will see both styles online, so you need to recognize both.

Implicit (pyplot) style Explicit (object-oriented) style
How it works plt silently tracks the “current” figure and Axes You create fig and ax and call methods on them
Looks like plt.plot(), plt.xlabel() ax.plot(), ax.set_xlabel()
Good for Very quick, throwaway plots Everything else, especially multiple plots

In this course we use the explicit style. It scales cleanly from one plot to many, and it is always clear which plot you are modifying.

x = [1, 2, 3, 4]
y = [2, 4, 6, 8]

# IMPLICIT STYLE: plt manages the figure and Axes behind the scenes
plt.plot(x, y, marker="o")
plt.title("Implicit style")
plt.xlabel("Acceleration (m/s$^2$)")
plt.ylabel("Force (N)")
plt.show()

# EXPLICIT STYLE: we create the Figure and Axes ourselves
fig, ax = plt.subplots()          # one Figure containing one Axes

ax.plot(x, y, marker="o")
ax.set_title("Explicit style")
ax.set_xlabel("Acceleration (m/s$^2$)")
ax.set_ylabel("Force (N)")
plt.show()

Same plot, slightly different names. Most Axes methods just add set_:

pyplot Axes method
plt.title() ax.set_title()
plt.xlabel() / plt.ylabel() ax.set_xlabel() / ax.set_ylabel()
plt.xlim() / plt.ylim() ax.set_xlim() / ax.set_ylim()
plt.xticks() ax.set_xticks()
plt.plot(), plt.scatter(), plt.legend(), plt.grid() ax.plot(), ax.scatter(), ax.legend(), ax.grid() (same name)

Tip: $...$ inside a label renders math (LaTeX), e.g. "m/s$^2$" becomes m/s².

4. The 5-step recipe

Nearly every plot you ever make follows the same five steps. Memorize this template and reuse it.

  1. Data: get or create your x and y values
  2. Create: fig, ax = plt.subplots(figsize=(width, height)) (size in inches)
  3. Plot: ax.plot(...), ax.scatter(...), ax.bar(...), …
  4. Label: title, axis labels with units, legend
  5. Save / show: fig.savefig(...), then plt.show()
# 1. DATA: approximate average daily high temperature in Washington, DC
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
dc_high = [44, 48, 57, 68, 77, 86, 90, 88, 81, 70, 59, 48]

# 2. CREATE
fig, ax = plt.subplots(figsize=(8, 4))

# 3. PLOT
ax.plot(months, dc_high, marker="o")

# 4. LABEL
ax.set_title("Washington, DC: average daily high by month")
ax.set_xlabel("Month")
ax.set_ylabel("Temperature (°F)")

# 5. SAVE / SHOW
# fig.savefig("dc_temps.png", dpi=300, bbox_inches="tight")   # (covered in Section 11)
plt.show()

Notice that x can be text (the month names). Matplotlib treats them as ordered categories.

5. Subplots: many Axes in one Figure

plt.subplots(nrows, ncols) creates a grid of Axes.

  • With one plot, ax is a single Axes object
  • With several plots, you get back a NumPy array of Axes, so you pick one with indexing:
    • One row or one column: axs[0], axs[1], …
    • A 2D grid: axs[row, col], e.g. axs[0, 1] is top row, second column
x = np.linspace(0, 2 * np.pi, 200)

fig, axs = plt.subplots(1, 2, figsize=(10, 3.5))   # 1 row, 2 columns
print(type(axs), axs.shape)

axs[0].plot(x, np.sin(x))
axs[0].set_title("sin(x)")

axs[1].plot(x, np.cos(x), color="tab:orange")
axs[1].set_title("cos(x)")

fig.suptitle("Two Axes in one Figure")   # title for the whole Figure
plt.show()
<class 'numpy.ndarray'> (2,)

Three settings that make subplots look right:

  • layout="constrained": automatically spaces plots so labels never overlap (use it every time)
  • sharex=True / sharey=True: subplots use the same axis range, which makes them directly comparable
  • for ax in axs.flat: loops over every Axes in a grid, so you can apply the same settings to all of them
funcs  = [np.sin, np.cos, np.tanh, np.arctan]
names  = ["sin(x)", "cos(x)", "tanh(x)", "arctan(x)"]
x = np.linspace(-3, 3, 400)

fig, axs = plt.subplots(2, 2, figsize=(9, 6), sharex=True, layout="constrained")

for ax, f, name in zip(axs.flat, funcs, names):
    ax.plot(x, f(x))
    ax.set_title(name)
    ax.set_ylim(-1.7, 1.7)
    ax.grid(alpha=0.3)

# Label only the outer edges of the grid
for ax in axs[1, :]:
    ax.set_xlabel("x (radians)")
for ax in axs[:, 0]:
    ax.set_ylabel("f(x)")

fig.suptitle("Four functions on a 2 x 2 grid")
plt.show()

6. Choosing the right plot type

Start from the question, not the chart. Then pick the plot that answers it.

Your question Plot type Axes method
How does something change over time or an ordered variable? Line ax.plot()
How are two numeric variables related? Scatter ax.scatter()
How do categories compare? Bar ax.bar() / ax.barh()
How is one numeric variable distributed? Histogram ax.hist()

6.1 Line plot: change over an ordered x

  • Call ax.plot() once per line; each call adds to the same Axes
  • Give each line a label= and call ax.legend() to identify them
# Approximate average daily highs (°F)
seattle_high = [48, 50, 54, 59, 65, 70, 76, 77, 71, 60, 51, 46]

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(months, dc_high,      marker="o", label="Washington, DC")
ax.plot(months, seattle_high, marker="s", label="Seattle, WA")

ax.set_title("DC summers are much hotter than Seattle's")
ax.set_xlabel("Month")
ax.set_ylabel("Average daily high (°F)")
ax.legend()
plt.show()

6.2 Scatter plot: relationship between two variables

  • Each point is one observation; no lines connect them
  • Encode a third variable with color (c=) and add a colorbar to explain it
n = 120
hours_studied = rng.uniform(0, 10, n)
hours_slept   = rng.uniform(4, 9, n)
exam_score    = np.clip(40 + 4 * hours_studied + 3 * hours_slept + rng.normal(0, 6, n), 0, 100)

fig, ax = plt.subplots(figsize=(7, 5))
points = ax.scatter(hours_studied, exam_score, c=hours_slept, cmap="viridis",
                    s=50, edgecolor="black", linewidth=0.5)

fig.colorbar(points, ax=ax, label="Hours slept the night before")
ax.set_title("More study (and more sleep) means higher scores")
ax.set_xlabel("Hours studied")
ax.set_ylabel("Exam score (%)")
plt.show()

6.3 Bar chart: compare categories

  • ax.bar(categories, values) for vertical bars
  • ax.barh() for horizontal bars: better when category names are long or there are many categories
  • Order the bars (largest to smallest) so the ranking is obvious at a glance
  • ax.bar_label() writes the value on each bar
languages = ["Python", "R", "SQL", "JavaScript", "Julia"]
n_students = [42, 30, 25, 12, 4]            # illustrative survey counts

fig, ax = plt.subplots(figsize=(7, 4))
bars = ax.bar(languages, n_students, color="tab:blue")
ax.bar_label(bars)
ax.set_ylim(0, 48)                           # headroom so the top label fits

ax.set_title("Languages students have used before")
ax.set_xlabel("Language")
ax.set_ylabel("Number of students")
plt.show()

6.4 Histogram: distribution of one variable

  • Splits the values into bins and counts how many fall in each
  • The number of bins changes the story: too few hides detail, too many looks noisy
scores = rng.normal(loc=75, scale=10, size=500)

fig, axs = plt.subplots(1, 3, figsize=(12, 3.5), layout="constrained")
for ax, bins in zip(axs, [5, 25, 200]):
    ax.hist(scores, bins=bins, color="tab:purple")
    ax.set_title(f"bins = {bins}")
    ax.set_xlabel("Exam score (%)")
axs[0].set_ylabel("Number of students")
fig.suptitle("Same data, three bin choices")
plt.show()

7. Styling: colors, lines, and markers

Every plotting method accepts keyword arguments that control its look. The most useful ones:

Keyword What it controls Examples
color Color "red", "tab:blue", "#1f77b4", "C0"
linewidth (lw) Line thickness (points) 1, 2.5
linestyle (ls) Line pattern "-", "--", ":", "-.", "none"
marker Point symbol "o", "s", "^", "x", "."
markersize (ms) Marker size (plot) 4, 10
s Marker size (scatter, it is an area) 20, 100
alpha Transparency, 0 (invisible) to 1 (solid) 0.3
label Name shown in the legend "Measured"

Ways to specify a color:

  • Named: "red", "black", "gray"
  • Tableau palette (the default, readable): "tab:blue", "tab:orange", "tab:green", …
  • Hex code: "#FF0000" is red ("#RRGGBB", pick codes at https://htmlcolorcodes.com)
  • Default color cycle: "C0", "C1", …, "C9" (the colors Matplotlib uses automatically, in order)
x = np.arange(10)

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, x + 0, color="tab:blue",  linestyle="-",  marker="o", label='solid, "o"')
ax.plot(x, x + 3, color="tab:red",   linestyle="--", marker="s", label='dashed, "s"')
ax.plot(x, x + 6, color="#2ca02c",   linestyle=":",  marker="^", label='dotted, "^"', markersize=9)
ax.plot(x, x + 9, color="black",     linestyle="-.", linewidth=3, label="dash-dot, thick")

ax.set_title("Line styles, markers, and colors")
ax.legend()
plt.show()

Use alpha to fix overplotting. When thousands of points pile up, a solid scatter becomes a blob. Transparency reveals where the data is dense.

big_x = rng.normal(0, 1, 5000)
big_y = big_x + rng.normal(0, 1, 5000)

fig, axs = plt.subplots(1, 2, figsize=(10, 4), sharey=True, layout="constrained")
axs[0].scatter(big_x, big_y, s=10)
axs[0].set_title("alpha = 1 (default): a blob")
axs[1].scatter(big_x, big_y, s=10, alpha=0.1)
axs[1].set_title("alpha = 0.1: density is visible")
plt.show()

Colormaps (cmap=) map numbers to colors, used by scatter(c=...), heatmaps, and images.

  • Ordered data (low to high): a sequential map like "viridis" (default), "plasma", "Blues"
  • Data with a meaningful center (e.g. negative vs. positive): a diverging map like "coolwarm" or "RdBu"
  • Avoid "jet" and rainbow maps: they create fake boundaries and fail for colorblind readers
  • Full list: https://matplotlib.org/stable/users/explain/colors/colormaps.html

8. Titles, labels, legends, and annotations

Command What it adds
ax.set_title("...") Title above one Axes
fig.suptitle("...") Title above the whole Figure
ax.set_xlabel("..."), ax.set_ylabel("...") Axis labels (always include units)
ax.legend(loc="upper left", fontsize=12) Legend built from every label=
ax.text(x, y, "...") Text at data coordinates (x, y)
ax.annotate("...", xy=..., xytext=..., arrowprops=...) Text with an arrow pointing at a spot
ax.axhline(y) / ax.axvline(x) Horizontal / vertical reference line

Every text command accepts fontsize=, color=, and fontweight="bold".

Shortcut: ax.set(title=..., xlabel=..., ylabel=..., xlim=..., ylim=...) sets several properties in one call.

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(scores, bins=25, color="lightgray", edgecolor="white")

mean_score = scores.mean()
ax.axvline(mean_score, color="tab:red", linewidth=2, label=f"Mean = {mean_score:.1f}%")
ax.axvline(60, color="black", linestyle="--", label="Passing threshold (60%)")

ax.annotate("Students at risk",
            xy=(55, 8), xytext=(45, 45),
            arrowprops=dict(arrowstyle="->", color="black"),
            fontsize=12)

ax.set(title="Distribution of exam scores (n = 500)",
       xlabel="Exam score (%)",
       ylabel="Number of students")
ax.legend(loc="upper right")
plt.show()

9. Controlling the axes: limits, ticks, scales, grid

Command Purpose
ax.set_xlim(lo, hi) / ax.set_ylim(lo, hi) Zoom to a range
ax.set_xticks([...]) Choose where ticks go
ax.set_xticks([...], ["a", "b", ...]) Choose ticks and their text labels
ax.tick_params(labelsize=14, rotation=45) Tick label size / rotation
ax.set_yscale("log") Logarithmic axis
ax.grid(True, alpha=0.3) Light background grid

When to use a log scale: data that spans several orders of magnitude, or grows exponentially. On a log axis, exponential growth becomes a straight line.

hours = np.arange(0, 25)
bacteria = 100 * 2 ** hours              # population doubles every hour

fig, axs = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")

axs[0].plot(hours, bacteria, marker=".")
axs[0].set_title("Linear y-axis: early growth is invisible")

axs[1].plot(hours, bacteria, marker=".")
axs[1].set_yscale("log")
axs[1].set_title("Log y-axis: steady doubling is a straight line")

for ax in axs:
    ax.set_xlabel("Time (hours)")
    ax.set_ylabel("Bacteria count")
    ax.set_xticks([0, 6, 12, 18, 24])
    ax.grid(True, alpha=0.3)
plt.show()

10. Changing the defaults: rcParams

Instead of passing fontsize= to every single command, change Matplotlib’s defaults.

  • Defaults live in plt.rcParams, which works like a Python dictionary
  • Permanent (for the rest of the notebook): plt.rcParams.update({...})
  • Temporary (one plot only): with plt.rc_context({...}):
  • Style sheets (pre-made looks, e.g. "ggplot"): plt.style.use("ggplot"); list them with plt.style.available
print("Default figure size (inches):", plt.rcParams["figure.figsize"])
print("Default font size:           ", plt.rcParams["font.size"])
Default figure size (inches): [6.4, 4.8]
Default font size:            10.0
# PERMANENT: bigger, more readable defaults for every plot from here on
plt.rcParams.update({
    "font.size": 14,
    "axes.titlesize": 16,
    "axes.labelsize": 14,
    "legend.fontsize": 12,
    "figure.figsize": (8, 5),
})

# To undo all changes and restore Matplotlib's factory defaults:
# plt.rcdefaults()

Tip: put a plt.rcParams.update({...}) cell at the top of every notebook you write. Every plot instantly looks more consistent and readable.

11. Saving figures

fig.savefig("my_plot.png", dpi=300, bbox_inches="tight")
  • File type comes from the extension
    • .png: images for slides, websites, reports (raster; set dpi=300 for sharp results)
    • .pdf / .svg: vector graphics that stay sharp at any zoom (best for papers and LaTeX)
  • bbox_inches="tight": trims extra white space and prevents labels from being cut off
  • Save before plt.show(): in scripts, show() can clear the figure, giving you a blank file
fig, ax = plt.subplots()
ax.plot(months, dc_high, marker="o")
ax.set(title="DC average daily high", xlabel="Month", ylabel="Temperature (°F)")

fig.savefig("dc_temps.png", dpi=300, bbox_inches="tight")   # 1. save
fig.savefig("dc_temps.pdf", bbox_inches="tight")
plt.show()                                                   # 2. then show

print("Saved dc_temps.png and dc_temps.pdf to the current folder")

Saved dc_temps.png and dc_temps.pdf to the current folder

12. From default to professional

Guidelines for good visualizations

These are the minimum standard for every plot you submit in the DSAN program. Plots that ignore them consistently lose points.

  1. Descriptive labels with units
    • "price" is bad: price of what? in what currency?
    • "S&P 500 index price (US dollars)" is good
  2. Large fonts
    • Plots end up in slides and must be readable from the back of the room
    • Roughly 14 to 20 pt for labels and ticks; not comically large
  3. Don’t overplot
    • One or two messages per plot; split the rest into subplots or separate figures
  4. Always have a message
    • No “plots for plots’ sake”; a good title often states the takeaway
  5. No overlapping text
    • Use layout="constrained", rotate tick labels, or move the legend

Before and after

Same data both times: noisy measurements of a spring that slowly stops bouncing.

t = np.linspace(0, 20, 80)                               # time (s)
model = 10 * np.exp(-t / 6) * np.cos(2 * t)              # true motion (cm)
measured = model + rng.normal(0, 0.8, t.size)            # noisy sensor readings

# BEFORE: pure defaults
plt.rcdefaults()          # temporarily go back to factory defaults for a fair comparison
fig, ax = plt.subplots()
ax.plot(t, measured)
ax.plot(t, model)
plt.show()

What’s wrong: no title, no labels, no units, no legend, tiny fonts, and it is unclear which line is data and which is the model.

# AFTER: every guideline applied
t_smooth = np.linspace(0, 20, 500)
model_smooth = 10 * np.exp(-t_smooth / 6) * np.cos(2 * t_smooth)
FS = 16

fig, ax = plt.subplots(figsize=(10, 5.5), layout="constrained")

ax.plot(t, measured, "o", color="tab:red", markersize=6, alpha=0.6, label="Sensor measurements")
ax.plot(t_smooth, model_smooth, color="tab:blue", linewidth=2.5, label="Damped oscillator model")
ax.plot(t_smooth,  10 * np.exp(-t_smooth / 6), color="gray", linestyle="--", linewidth=1.5,
        label="Decay envelope")
ax.plot(t_smooth, -10 * np.exp(-t_smooth / 6), color="gray", linestyle="--", linewidth=1.5)

ax.annotate("Amplitude halves every ~4 s",
            xy=(4.2, 5.0), xytext=(7, 8), fontsize=FS - 2,
            arrowprops=dict(arrowstyle="->", color="black"))

ax.set_title("A damped spring: the model matches the measurements", fontsize=FS + 4)
ax.set_xlabel("Time (s)", fontsize=FS)
ax.set_ylabel("Displacement from rest (cm)", fontsize=FS)
ax.tick_params(labelsize=FS - 2)
ax.set_xlim(0, 20)
ax.set_ylim(-11, 11)
ax.grid(alpha=0.3)
ax.legend(fontsize=FS - 2, loc="lower right")

fig.savefig("damped_spring.png", dpi=300, bbox_inches="tight")
plt.show()

Checklist that the “after” plot satisfies: clear takeaway in the title, units on both axes, readable fonts, data and model visually distinct (markers vs. line), legend, light grid, one annotation that supports the message, nothing overlapping.

13. Common errors and how to fix them

Symptom / error message Cause Fix
AttributeError: 'Axes' object has no attribute 'xlabel' Mixed up pyplot and Axes names Use ax.set_xlabel() (see table in Section 3)
AttributeError: 'numpy.ndarray' object has no attribute 'plot' With subplots, axs is an array of Axes Index it: axs[0].plot() or axs[0, 1].plot()
ValueError: x and y must have same first dimension x and y have different lengths Check len(x), len(y)
Saved image is blank savefig() called after plt.show() Call fig.savefig() before plt.show()
No artists with labels found to put in legend Called ax.legend() but no label= given Add label="..." to each plot call
Labels or titles overlap Default spacing plt.subplots(..., layout="constrained")
Tick labels are crammed together Too many or long category names ax.tick_params(axis="x", rotation=45) or use barh
Two plots drawn on top of each other Reused the same ax Call plt.subplots() again for a new figure

14. Quick reference

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 5))                  # one plot
fig, axs = plt.subplots(2, 3, layout="constrained")     # grid of plots: axs[row, col]

ax.plot(x, y, color=, linestyle=, marker=, label=)      # line
ax.scatter(x, y, s=, c=, cmap=, alpha=)                 # scatter
ax.bar(categories, values) / ax.barh(...)               # bar
ax.hist(values, bins=)                                  # histogram

ax.set_title(); ax.set_xlabel(); ax.set_ylabel()        # text
ax.legend(); ax.annotate(); ax.text()
ax.set_xlim(); ax.set_ylim(); ax.set_xticks()           # axes
ax.set_yscale("log"); ax.grid(alpha=0.3)
ax.tick_params(labelsize=14)

fig.suptitle()                                          # figure-level
fig.colorbar(mappable, ax=ax)
fig.savefig("name.png", dpi=300, bbox_inches="tight")
plt.show()

Further resources

  • Matplotlib quick start guide: https://matplotlib.org/stable/users/explain/quick_start.html
  • Plot types overview (a visual menu of what is possible): https://matplotlib.org/stable/plot_types/index.html
  • Example gallery (find a plot, copy the code): https://matplotlib.org/stable/gallery/index.html
  • Official cheat sheets: https://matplotlib.org/cheatsheets/

References

Disclaimer: This document is not an original work. It contains content from many sources and is for educational purposes only.

Sources:

  • https://matplotlib.org/stable/tutorials/index.html
  • https://matplotlib.org/stable/tutorials/pyplot.html
  • https://matplotlib.org/stable/users/explain/quick_start.html
  • https://towardsdatascience.com/what-are-the-plt-and-ax-in-matplotlib-exactly-d2cf4bf164a9
  • https://docs.python.org/3/tutorial/