Matplotlib Tutorial: A Guide from First Plot to Polished Chart

A map of the Matplotlib tutorials: the basics, chart types, axes and ticks, legends and text, layouts, styling, and saving figures.

To make a chart in Matplotlib, create a figure with fig, ax = plt.subplots(), draw on the axes with a method such as ax.plot() or ax.bar(), and call plt.show(). This page is the map to the Matplotlib tutorials on this site, grouped by what you're trying to do. Newer ones are written for Matplotlib 3.11.

Grid of twelve Matplotlib charts: line, grouped bar, scatter, histogram, heatmap, subplot layout, contour, 3D, radar, stream graph, bubble and bump charts

Quick Example

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
online = [31, 35, 42, 40, 51, 58]
in_store = [48, 44, 45, 41, 39, 38]

fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(months, online, marker="o", label="Online")
ax.plot(months, in_store, marker="s", label="In store")
ax.set_title("Orders by Channel")
ax.set_ylabel("Orders (thousands)")
ax.legend()
plt.show()

Matplotlib line chart in which online orders rise from 31 to 58 thousand while in-store orders fall from 48 to 38 thousand

Where Should I Start With Matplotlib?

Step Question Tutorial
1. Objects What are fig, ax and plt? Figure vs Axes
2. First chart How do I draw and style lines? Line plots
3. Label it How do I add titles and axis labels? Titles and subtitles and axis labels
4. Explain it How do I add a legend? Legends
5. Combine How do I put several plots in one figure? Subplots
6. Export How do I save it as a file? savefig

Keep the Matplotlib cheat sheet open as you go, and read plot not showing if no window appears.

Which Matplotlib Chart Should I Use?

To choose by appearance, browse the Python Chart Gallery.

To show Method Tutorial
A trend over time ax.plot Line plots
Totals over time ax.stackplot Area charts, stream graphs
Values by category ax.barh Sorted horizontal bars, styled bar charts
Several series by category ax.bar Grouped bars, stacked bars with labels
Bars colored by a rule ax.bar(color=...) Color bars by value
A cleaner ranking ax.hlines, ax.stem Lollipop and dot plots
Rank changes ax.plot Bump charts
Before and after ax.plot Slope charts
A value against a target ax.barh Bullet charts
The biggest causes ax.bar, ax.twinx Pareto charts
Parts of a whole ax.pie Pie charts, donut charts
Shares across two categories ax.bar Marimekko and mosaic charts
One distribution ax.hist Histograms
Distributions by group ax.boxplot Box plots
Ages by sex ax.barh Population pyramids
Two numeric variables ax.scatter Scatter plots
A third variable as size ax.scatter(s=...) Bubble charts
Uncertainty ax.errorbar Error bars
A grid of values ax.imshow Heatmaps, correlation matrices
A surface in 2D ax.contourf Contour plots
Three dimensions projection="3d" 3D plots
Several measures per item polar axes Radar charts
Many small trends plt.subplots Sparklines and small multiples
An image or array ax.imshow Display images
Density of many points ax.hexbin, ax.hist2d Hexbin and 2D histograms
Values that hold, then jump ax.step, ax.stem Step and stem plots
A vector field ax.quiver, ax.streamplot Quiver and stream plots
Exact numbers with the chart ax.table Add a table

Axes, Limits, and Ticks

You want to Tutorial
Set the x and y range Axis limits
Match the x and y scales Aspect ratio and equal axes
Skip an empty range Broken axis
Flip an axis Invert an axis
Use a log scale Logarithmic scales
Plot two scales on one chart Dual y-axes
Cross the axes at zero Center the spines
Control where ticks go Ticks and tick frequency
Rotate crowded labels Rotate axis labels
Resize or restyle tick labels Tick label font size
Remove ticks or labels Hide ticks and labels
Show dollars or percentages Currency and percentage formats
Format dates Date formatting

Legends, Text, and Annotations

You want to Tutorial
Move the legend off the data Legend outside the plot
Reorder or rename entries Legend order and names
Spread entries across columns Multi-column legends
Change the legend title or font Legend title and font size
Add a source line or footnote Title, subtitle and footnotes
Label individual points Annotate data points
Point at something Annotations with arrows
Write equations LaTeX in labels
Mark a threshold Horizontal and vertical lines
Shade an event or period Highlight a date range

Subplots and Figure Layout

You want to Tutorial
Change the figure size Figure size
Make panels of different sizes subplot_mosaic and GridSpec
Share an axis between panels Shared axes
Zoom in on part of a chart Inset and zoomed axes
Stop labels overlapping Subplot spacing

Colors and Styling

You want to Tutorial
Pick colors or a colormap Colormaps and colors
Use brand colors Hex and RGB colors
Build your own colormap Custom colormaps
Add or adjust a color scale Colorbars
Change markers Markers
Style the gridlines Grids
Add stripes or dots to fills Hatch patterns
Remove the box around the plot Remove spines
Fade the area under a line Gradient fills
Use a different font Custom fonts
Restyle in one line Style sheets
Make a dark chart Dark mode
Set your own defaults rcParams

Saving, Animating, and Embedding

You want to Tutorial
Export PNG, SVG or PDF savefig
Export without a background Transparent backgrounds
Save a GIF or MP4 Animations
Put a chart in a desktop app Tkinter and PyQt
Zoom and add sliders in a notebook Interactive Jupyter plots

Should I Use pyplot or the Object-Oriented Interface?

plt.plot() draws on whichever axes is current, which is fine for a quick single chart. ax.plot() names the axes it draws on, so it stays clear with several panels or when a function builds a chart. Most method names carry over with a set_ prefix: plt.title() becomes ax.set_title(). Figure vs Axes has the full translation table.

Common Matplotlib Problems

Problem Fix Details
No window or inline chart appears Call plt.show() and check the backend Plot not showing
The saved image is blank Call fig.savefig() before plt.show() savefig
Labels are cut off in the saved file Pass bbox_inches="tight" savefig
Subplot titles and labels overlap Pass layout="constrained" to plt.subplots() Subplot spacing
The legend covers the data Move it with bbox_to_anchor Legend outside
X labels run together ax.tick_params(axis="x", labelrotation=45) Rotate labels

Similar Topics