Pynions

Matplotlib in Python: The Axes API, Cleaner Styles, and 3.11 Changes

Learn Matplotlib the way its docs suggest: the Axes API, subplots, styles that don't look dated, and tested 3.11.2 code for the changes that break old snippets.

Updated 11 min read
Printed bar chart and pie chart on a desk next to a red binder

Matplotlib is the Python plotting library that Seaborn and pandas plotting build on. Its official site describes it as "a comprehensive library for creating static, animated, and interactive visualizations in Python." The current release is Matplotlib 3.11.2, published in September 2026.

The package pulled 207,239,621 downloads in the last month, as of 2 December 2026. This guide uses the explicit Axes interface the Matplotlib docs suggest for reusable code, and every code block was tested on Python 3.15.2 with Matplotlib 3.11.2.

It runs from your first figure to a reusable house style and the 3.11 changes that break older tutorials.

Key Takeaways

  • Matplotlib has two interfaces: the explicit Axes interface (fig, ax = plt.subplots(), then ax.plot()) and the implicit pyplot interface (plt.plot()), which acts on whatever Figure and Axes it tracked last.
  • The docs suggest the object-oriented (Axes) style for complicated plots and for code you reuse. Keep pyplot for quick interactive checks.
  • Matplotlib 3.11 requires Python 3.11 and NumPy 1.25 or newer. It added grouped_bar(), figure sizes in pixels or centimetres, and the Okabe-Ito, petroff6 and petroff8 color sequences.
  • 3.11 removed matplotlib.cm.get_cmap, the labels= argument of boxplot, and plot_date. Old snippets that use them now fail.
  • Close figures you create in a loop with plt.close(fig). Matplotlib warns once more than 20 figures are open.

What Is Matplotlib?

Matplotlib draws 2D charts from Python data: line plots, scatter plots, bar charts, histograms, images, contour plots, and many more. It renders to PNG, SVG, PDF, and other formats, displays figures in a desktop window or inline in Jupyter Notebook, and can embed charts in GUI applications.

The original author, John D. Hunter (1968-2012), started it by emulating MATLAB's plotting commands. The project notes that Matplotlib is independent of MATLAB and "can be used in a Pythonic, object-oriented way." That history explains why two interfaces exist today.

Matplotlib homepage with the headline Matplotlib: Visualization with Python

Many higher-level libraries sit on top of it. Seaborn is "based on matplotlib," and the pandas DataFrame.plot() method draws with Matplotlib by default. If you work through the Python data analysis workflow, Matplotlib is the layer that turns your results into charts.

Why Matplotlib Matters in 2027

Matplotlib 3.11.0 arrived on 11 June 2026, followed by 3.11.1 on 17 July and 3.11.2 on 10 September 2026, per the release notes. The license is based on the PSF license, and the core uses only BSD-compatible code.

The 3.11 release matters for anyone copying older examples. It raised the minimum Python version from 3.10 to 3.11 and removed functions that were deprecated in earlier releases. Older tutorials may still call those functions, so knowing the changes saves you a confusing traceback.

How Matplotlib Works: Figures, Axes, and Two Interfaces

A Matplotlib chart is a tree of objects. The Figure is the whole canvas, each Axes is one plotting area inside it, and everything you draw (lines, bars, text, legends) is an Artist attached to an Axes.

The Matplotlib docs describe two ways to build that tree. The explicit "Axes" interface, also called the object-oriented interface, "is how Matplotlib is implemented." The implicit pyplot interface "keeps track of the last Figure and Axes created" and adds Artists to the object it thinks you want.

Install Matplotlib 3.11.2

Every code block below ran in a clean virtual environment on Python 3.15.2 with matplotlib 3.11.2, numpy 2.5.5, and pandas 3.1.2. Each block is a standalone script that saves its chart as a PNG next to it.

Shell
python -m venv .venv
source .venv/bin/activate
pip install -q matplotlib==3.11.2 numpy==2.5.5 pandas==3.1.2
python -c "import matplotlib; print(matplotlib.__version__)"
Text
3.11.2

Matplotlib 3.11 itself needs Python 3.11 or newer, but NumPy 2.5.5 requires Python 3.12, so this pinned set needs Python 3.12 or later. The installation page also lists conda install -c conda-forge matplotlib and uv add matplotlib. If you manage Python with uv, the docs ask for uv 0.8.7 or newer so the tkagg backend can open plot windows; see our uv guide for the basics.

Your First Figure With the Axes Interface

Python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 200)

fig, ax = plt.subplots(figsize=(6.4, 4), layout="constrained")
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)", linestyle="--")
ax.set(title="My first Matplotlib figure", xlabel="x", ylabel="value")
ax.legend()

fig.savefig("first_plot.png", dpi=150)
print(type(fig).__name__, type(ax).__name__)
print(tuple(int(v) for v in fig.get_size_inches() * 150))
Text
Figure Axes
(960, 600)

The plt.subplots() call returns the Figure and one Axes, and every later call is a method on one of them. The layout="constrained" option keeps titles and labels from overlapping, and dpi=150 turns the 6.4 by 4 inch figure into a 960 by 600 pixel PNG. To open a window instead of saving a file, call plt.show() at the end of the script.

Why pyplot Surprises You in Bigger Scripts

Python
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2)
plt.title("Which subplot gets this?")

print(repr(ax1.get_title()), repr(ax2.get_title()))
print(plt.gca() is ax2)
Text
'' 'Which subplot gets this?'
True

plt.title() did not ask which subplot you meant. It set the title on the current Axes, which is the last one plt.subplots() created. In a two-line script that is easy to spot; in a 200-line report it is how a title lands on the wrong chart.

The quick start guide says: "In general, we suggest using the OO style, particularly for complicated plots, and functions and scripts that are intended to be reused as part of a larger project." The same page calls pyplot "very convenient for quick interactive work" and says the old from pylab import * style "is strongly deprecated."

Write Plot Functions That Take an Axes

The docs recommend a helper signature for repeated charts: pass the Axes in, draw on it, and return what you drew. Because the function never touches global state, you can reuse it in any grid, notebook, or report.

Task

Implicit pyplot

Explicit Axes

Create a figure

plt.figure()

fig, ax = plt.subplots()

Plot a line

plt.plot(x, y)

ax.plot(x, y)

Set the title

plt.title("T")

ax.set_title("T") or ax.set(title="T")

Axis labels

plt.xlabel("x")

ax.set_xlabel("x")

Legend

plt.legend()

ax.legend()

Save

plt.savefig("f.png")

fig.savefig("f.png")

Building Common Charts: Subplots, Lines, Scatter, Bars, and Histograms

Most real charts need more than one panel. plt.subplots(rows, cols) returns a NumPy array of Axes, so axs[0, 1] is the top-right panel and each one gets its own methods.

A Four-Panel Figure With plt.subplots

Python
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(42)
days = np.arange(1, 31)
signups = 120 + np.cumsum(rng.integers(-5, 12, size=30))
latency = rng.normal(loc=180, scale=25, size=500)
plans = ["Free", "Pro", "Team"]
revenue = [0, 4200, 6900]

fig, axs = plt.subplots(2, 2, figsize=(10, 7), layout="constrained")
axs[0, 0].plot(days, signups, marker="o", markersize=3)
axs[0, 0].set(title="Daily signups", xlabel="Day", ylabel="Signups")

axs[0, 1].scatter(latency[:-1], latency[1:], s=8, alpha=0.5)
axs[0, 1].set(title="Latency vs next request", xlabel="ms", ylabel="ms")

counts, edges, _ = axs[1, 0].hist(latency, bins=10, edgecolor="white")
axs[1, 0].set(title="Latency distribution", xlabel="ms", ylabel="Requests")

bars = axs[1, 1].bar(plans, revenue)
axs[1, 1].bar_label(bars, fmt="${:,.0f}")
axs[1, 1].set(title="Revenue by plan", ylabel="USD")

fig.savefig("dashboard.png", dpi=150)
print(axs.shape)
print(signups[-1])
print(counts.astype(int))
Text
(2, 2)
233
[  2  13  41  76 118 123  70  38  13   6]
Four-panel Matplotlib figure with a line chart of daily signups, a latency scatter plot, a latency histogram, and a labeled revenue bar chart

The seeded random generator makes the output repeatable, so your histogram counts should match the ten numbers above. The ax.hist() method returns the counts and bin edges along with the drawn bars, handy when a report needs the numbers. The ax.bar_label() method writes each bar's value on top of it with a format string.

Uneven Layouts With subplot_mosaic

When panels need different sizes, subplot_mosaic builds the grid from a text picture. The official Matplotlib account introduced it as a way to "pass us a layout id'ed on name."

Python
import matplotlib.pyplot as plt

fig, axd = plt.subplot_mosaic(
    """
    AAB
    CCB
    """,
    figsize=(9, 5),
    layout="constrained",
)
for name, ax in axd.items():
    ax.set_title(f"Axes {name}")

fig.savefig("mosaic.png", dpi=150)
print(sorted(axd))
Text
['A', 'B', 'C']

Each letter becomes one Axes, and repeating a letter makes that Axes span several cells. Here B fills the whole right column, while A and C share the left two-thirds. You get back a dictionary, so axd["B"] is easier to read than a row and column index.

Grouped Bars and Pixel Sizes in Matplotlib 3.11

Two 3.11 additions remove common boilerplate. The new grouped_bar() method accepts lists, dicts, 2D arrays, or pandas DataFrames, and figure sizes now take a unit string: "in", "cm", or "px".

Python
import matplotlib.pyplot as plt

quarters = ["Q1", "Q2", "Q3", "Q4"]
sales = {
    "2025": [12, 15, 14, 18],
    "2026": [14, 17, 19, 22],
}

fig, ax = plt.subplots(figsize=(800, 450, "px"), layout="constrained")
ax.grouped_bar(sales, tick_labels=quarters)
ax.legend(title="Year")
ax.set(title="Sales by quarter", ylabel="Units (thousands)")

fig.savefig("grouped_bar.png")
print(fig.get_size_inches(), fig.dpi)
Text
[8.  4.5] 100.0

One grouped_bar() call places every bar and tick label, where earlier code offset each group's bars by hand. At the default 100 dpi, 800 by 450 pixels becomes 8 by 4.5 inches, and the saved PNG comes out at 800 by 450 pixels.

Styling Matplotlib So It Doesn't Look Dated

The default look is blue, orange, and green lines, a full box around every chart, and no grid. You can change all of it without touching each plot, through style sheets and rcParams.

The customizing guide sets the order: style sheets take precedence over your matplotlibrc file, and a style sheet can only set style-related rcParams. On 3.11.2, plt.style.available lists 28 built-in styles.

Matplotlib Style sheets reference page with example charts drawn in the default style

Try a Built-in Style for One Figure

Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import to_hex

x = np.linspace(0, 10, 100)

with plt.style.context("petroff10"):
    print([to_hex(c) for c in plt.rcParams["axes.prop_cycle"].by_key()["color"][:3]])
    fig, ax = plt.subplots(layout="constrained")
    for shift in range(4):
        ax.plot(x, np.sin(x + shift), label=f"shift {shift}")
    ax.legend()
    fig.savefig("petroff10.png", dpi=150)

print([to_hex(c) for c in plt.rcParams["axes.prop_cycle"].by_key()["color"][:3]])
Text
['#3f90da', '#ffa90e', '#bd1f01']
['#1f77b4', '#ff7f0e', '#2ca02c']

plt.style.context() applies a style inside the with block and restores the defaults after it, which the second line proves. petroff10 arrived in Matplotlib 3.10.0, and 3.11 added the six-color petroff6 and eight-color petroff8 versions. They come from Matthew A. Petroff's paper on accessible color sequences.

Save a House Style as an .mplstyle File

Python
from pathlib import Path

import matplotlib.pyplot as plt
from matplotlib.colors import to_hex

Path("clean.mplstyle").write_text("""\
axes.spines.top: False
axes.spines.right: False
axes.grid: True
axes.grid.axis: y
axes.axisbelow: True
grid.alpha: 0.3
axes.titlesize: large
axes.titleweight: bold
axes.prop_cycle: cycler(color='okabe_ito')
figure.dpi: 150
savefig.bbox: tight
""")

plt.style.use("./clean.mplstyle")
fig, ax = plt.subplots()
ax.bar(["A", "B", "C"], [3, 5, 2])
ax.set_title("Cleaner defaults")
fig.savefig("clean_style.png")

print(plt.rcParams["axes.spines.top"], plt.rcParams["figure.dpi"])
print([to_hex(c) for c in plt.rcParams["axes.prop_cycle"].by_key()["color"][:3]])
Text
False 150.0
['#000000', '#e69f00', '#56b4e9']

The file removes the top and right spines, adds a light horizontal grid drawn behind the bars, bolds titles, and trims whitespace on save. The color line uses the Okabe-Ito sequence added in 3.11, whose colors stay distinguishable for common forms of color-vision deficiency and in print. Its first color is black, so put your most important series first or reorder the cycle.

To reuse the style across projects, save the file in the stylelib folder inside your Matplotlib config directory (matplotlib.get_configdir() prints it), then load it by name with plt.style.use("clean").

Style Options at a Glance

Approach

Scope

Best for

ax.set(...), method arguments

One Axes

One-off tweaks

plt.style.context("name")

One with block

Trying a style, mixed styles in one script

plt.style.use("file.mplstyle")

Rest of the script

A project-wide house style

matplotlibrc file

Every script that finds it

Machine-wide defaults

Matplotlib 3.11 Changes That Break Older Code

Snippets copied from older tutorials can target functions that no longer exist. The 3.11 API changes page lists the removals, and these two are easy to hit in copied code.

Python
import matplotlib
import matplotlib.pyplot as plt

try:
    matplotlib.cm.get_cmap("viridis")
except AttributeError as err:
    print("AttributeError:", err)

cmap = matplotlib.colormaps["viridis"]
print(cmap.name, cmap.N)

fig, ax = plt.subplots()
try:
    ax.boxplot([[1, 2, 3], [2, 3, 4]], labels=["a", "b"])
except TypeError as err:
    print("TypeError:", err)
ax.boxplot([[1, 2, 3], [2, 3, 4]], tick_labels=["a", "b"])
print([t.get_text() for t in ax.get_xticklabels()])
Text
AttributeError: module 'matplotlib.cm' has no attribute 'get_cmap'
viridis 256
TypeError: Axes.boxplot() got an unexpected keyword argument 'labels'. Did you mean 'label'?
['a', 'b']

What Was Removed, and What Replaces It

Old code

Status in 3.11

Use instead

matplotlib.cm.get_cmap("viridis")

Removed

matplotlib.colormaps["viridis"]

ax.boxplot(data, labels=[...])

Removed

ax.boxplot(data, tick_labels=[...])

ax.plot_date(dates, values)

Removed (deprecated since 3.9)

ax.plot(dates, values)

ax.boxplot(data, vert=False)

Deprecated

ax.boxplot(data, orientation="horizontal")

cmap.set_bad("red") and other in-place colormap edits

Pending deprecation

cmap.with_extremes(bad="red")

The matplotlib.pyplot.get_cmap shortcut still works, so only code that reaches into matplotlib.cm breaks. The API changes notes also say colormaps "are planned to become immutable in the long term." Build the habit now with with_extremes(), which returns a copy.

Pin Your Version in Shared Projects

Because 3.11 removed functions outright, an unpinned pip install matplotlib can break a notebook that worked last year. Pin matplotlib==3.11.2 in your requirements file or lockfile, and read the API changes page before you move to the next minor release.

Saving Figures and Plotting From pandas

Most Matplotlib output ends up in a file, a report, or a dashboard rather than a window. Two habits keep that reliable: close every figure you are done with, and let pandas hand its plots to an Axes you control.

Close Figures You Create in a Loop

Python
import warnings

import matplotlib.pyplot as plt

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    for i in range(21):
        fig, ax = plt.subplots()
        ax.plot([0, i])
        fig.savefig(f"chart_{i}.png")

print(len(plt.get_fignums()), "figures still open")
print(caught[0].category.__name__, str(caught[0].message)[:38])
plt.close("all")

for i in range(21):
    fig, ax = plt.subplots()
    ax.plot([0, i])
    fig.savefig(f"chart_{i}.png")
    plt.close(fig)

print(len(plt.get_fignums()), "figures still open")
Text
21 figures still open
RuntimeWarning More than 20 figures have been opened.
0 figures still open

pyplot tracks every figure it creates until you close it, and the pyplot.figure docs ask you to call pyplot.close on figures you are not using so pyplot can clean up the memory. Matplotlib warns once the count passes the figure.max_open_warning rcParam, which defaults to 20. plt.close(fig) after each savefig() keeps the count at zero.

Plot a pandas DataFrame on Your Own Axes

Python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
df = pd.DataFrame(
    {"visits": rng.integers(800, 1200, size=12), "signups": rng.integers(40, 90, size=12)},
    index=pd.date_range("2026-01-01", periods=12, freq="MS"),
)

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
df["visits"].plot(ax=ax, label="Visits")
ax2 = ax.twinx()
df["signups"].plot(ax=ax2, color="tab:orange", label="Signups")
ax.set(title="Visits and signups, 2026", ylabel="Visits")
ax2.set_ylabel("Signups")
fig.legend(loc="outside upper right")

fig.savefig("pandas_plot.png", dpi=150)
print(type(ax).__name__, ax2.get_ylabel())
print(df.index[0].date(), df.index[-1].date(), len(df))
Text
Axes Signups
2026-01-01 2026-12-01 12

Passing ax=ax to Series.plot() draws onto an Axes you created, so pandas plots mix with your own Matplotlib calls in one figure. The ax.twinx() call adds a second y-axis that shares the x-axis. With constrained layout, loc="outside upper right" makes space for the figure legend above the plot area.

For heavier analysis before plotting, see our guides to Python statistics and Polars.

When to Use Seaborn or Plotly Instead

Data practitioners on LinkedIn ask this question often, and their comparison posts describe Matplotlib as the foundational library with full control over every element. You pay for that control with more code, and two libraries cover the most common reasons to reach past it.

Seaborn "provides a high-level interface for drawing attractive and informative statistical graphics" and is built on Matplotlib, so its axes-level charts draw on Matplotlib Axes you can still adjust. Plotly "makes interactive, publication-quality graphs" for the browser and notebooks.

Library

Current version

Output

Pick it when

Matplotlib

3.11.2 (Sep 2026)

Static files (PNG, SVG, PDF) and interactive windows

You need exact control, print-ready figures, or custom layouts

Seaborn

0.13.2 (Jan 2024)

Matplotlib figures

You want statistical charts (distributions, regressions, categorical comparisons) from a DataFrame in one call

Plotly

7.2.0 (Nov 2026), MIT license

Interactive HTML charts

Readers need hover, zoom, and filtering in a browser or a web app

The two are not exclusive with Matplotlib. As one r/Python commenter wrote about Seaborn, "I have to reach for matplotlib to add some fairly basic elements," which is why learning the Axes API first pays off. For interactive data apps rather than single charts, compare Streamlit.

Common Matplotlib Mistakes to Avoid

Mixing plt.* Calls With Several Subplots

Calling plt.title() or plt.xlabel() after creating a grid edits only the last Axes, as the test above shows. Call the method on the Axes you mean, such as axs[0, 1].set_title().

Copying Snippets That Use Removed APIs

matplotlib.cm.get_cmap, boxplot(labels=...) and plot_date all fail on 3.11. Switch to matplotlib.colormaps[...], tick_labels=, and a plain ax.plot() with datetime values.

Never Closing Figures in Batch Jobs

Saving charts in a loop without plt.close(fig) keeps every figure in memory and triggers the 20-figure warning. Close each figure right after fig.savefig().

Styling Each Chart by Hand

Repeating ax.spines["top"].set_visible(False) and color lists in every script drifts out of sync. Put the settings in one .mplstyle file and load it with plt.style.use().

Leaving Layout to Chance

Without a layout engine, long tick labels and titles can overlap in subplot grids. Pass layout="constrained" to plt.subplots() or plt.subplot_mosaic(), as the chart examples here do.

Frequently Asked Questions

Sources

Related Articles