MATPLOTLIB
The Complete Visual Guide
30 chart types, explained in plain language — what each one is, when to reach for it, practical tips,
and ready-to-run code.
30
Chart Types 5
Categories 100%
Runnable Code
CONTENTS
Basic 2D Plots
1. Line Plot 4. Horizontal Bar
2. Scatter Plot 5. Histogram
3. Bar Chart 6. Pie Chart
Statistical & Distribution Plots
7. Box Plot 11. Stack Plot
8. Violin Plot 12. Area Plot
9. Stem Plot 13. Error Bar Plot
10. Step Plot
Grid, Density & Field Plots
14. Heatmap (imshow) 17. Filled Contour (contourf)
15. Image Plot (imshow) 18. Hexbin Plot
16. Contour Plot
Specialized Plots
19. Polar Plot 23. Spectrogram
20. Quiver Plot 24. Spy Plot
Page 1 | Matplotlib Complete Guide
21. Stream Plot 25. Table
22. Event Plot
3D Plots
26. 3D Line Plot 29. 3D Wireframe Plot
27. 3D Scatter Plot 30. 3D Bar Plot
28. 3D Surface Plot
Page 2 | Matplotlib Complete Guide
Basic 2D Plots
1 Line Plot
BASIC 2D PLOTS
WHAT IT IS
A line plot connects data points in order with straight line
segments. It is the default, most fundamental chart type in
Matplotlib and is created with [Link]().
WHEN TO USE IT
Use a line plot to show how a value changes over a continuous
variable, most commonly time. It is ideal for trends, time series
(stock prices, temperatures, sensor readings) and any dataset
where the order of points matters and you want to emphasize
continuity.
TIP
Add markers with the marker parameter to highlight individual
data points. Use [Link](True) for easier reading of values, and
combine multiple [Link]() calls on the same axes to compare
several series.
import [Link] as plt
x = [1,2,3,4,5]
y = [10,20,15,30,25]
[Link](x, y, marker='o', color='blue')
[Link]('Line Plot')
[Link]('X axis')
[Link]('Y axis')
[Link](True)
[Link]()
Page 3 | Matplotlib Complete Guide
2 Scatter Plot
BASIC 2D PLOTS
WHAT IT IS
A scatter plot draws each data point as an individual marker
without connecting lines, positioned according to its x and y
values.
WHEN TO USE IT
Use scatter plots to reveal the relationship or correlation between
two numeric variables, to spot clusters, outliers, or patterns in raw
data where the sequence of points is not meaningful (unlike a line
plot).
TIP
The 's' parameter controls marker size and can encode a third
variable. Combine size and color (a 'bubble chart') to visualize up
to four dimensions of data at once.
import [Link] as plt
x = [1,2,3,4,5,6,7,8]
y = [5,16,7,23,18,13,40,8]
[Link](x, y, color='green', marker='o', s=60)
[Link]('Scatter Plot')
[Link]('X axis')
[Link]('Y axis')
[Link](True)
[Link]()
Page 4 | Matplotlib Complete Guide
3 Bar Chart
BASIC 2D PLOTS
WHAT IT IS
A bar chart represents categorical data with rectangular bars
whose length is proportional to the value they represent,
arranged vertically along the x-axis.
WHEN TO USE IT
Use bar charts to compare discrete categories side by side, such
as sales by product, population by country, or scores by team.
They work best with a small-to-moderate number of categories.
TIP
Sort bars by value to make comparisons easier on the eye. Use
[Link] for vertical bars and consider grouped or stacked bars
when comparing sub-categories.
import [Link] as plt
categories = ['A','B','C','D','E']
values = [45,65,90,60,80]
[Link](categories, values, color='orange')
[Link]('Bar Chart')
[Link]('Categories')
[Link]('Values')
[Link]()
Page 5 | Matplotlib Complete Guide
4 Horizontal Bar
BASIC 2D PLOTS
WHAT IT IS
A horizontal bar chart is the same idea as a bar chart, but the
bars extend sideways from the y-axis instead of upward from the
x-axis.
WHEN TO USE IT
Use horizontal bars when category names are long (they read
better horizontally), when you have many categories to list, or
when ranking items from top to bottom such as a leaderboard.
TIP
Categories are usually listed top-to-bottom in the order supplied,
so sort your data beforehand if you want the largest value at the
top.
import [Link] as plt
categories = ['A','B','C','D','E']
values = [45,65,90,60,80]
[Link](categories, values, color='purple')
[Link]('Horizontal Bar')
[Link]('Values')
[Link]('Categories')
[Link]()
Page 6 | Matplotlib Complete Guide
5 Histogram
BASIC 2D PLOTS
WHAT IT IS
A histogram groups continuous numeric data into 'bins' and
draws a bar for each bin showing how many data points fall
inside it, revealing the shape of a distribution.
WHEN TO USE IT
Use a histogram to understand the distribution of a single
numeric variable: is it normal (bell-shaped), skewed, bimodal? It's
a first step in exploratory data analysis for things like test scores,
ages, or measurement errors.
TIP
The 'bins' parameter controls resolution — too few bins hides
structure, too many makes it noisy. Try a handful of bin counts
before settling on one.
import [Link] as plt
import numpy as np
[Link](0)
data = [Link](1000)
[Link](data, bins=10, color='skyblue', edgecolor='black')
[Link]('Histogram')
[Link]('Value')
[Link]('Frequency')
[Link]()
Page 7 | Matplotlib Complete Guide
6 Pie Chart
BASIC 2D PLOTS
WHAT IT IS
A pie chart divides a circle into slices, where each slice's angle is
proportional to its share of the total, making part-to-whole
relationships visible at a glance.
WHEN TO USE IT
Use a pie chart only when you want to show how a small number
of categories (ideally under 6) make up 100% of a whole, such as
market share or budget allocation. Avoid it for comparing many
categories or precise value comparisons — bar charts do that
better.
TIP
Use the 'explode' parameter to visually pull out and emphasize
one slice. Always include autopct to label percentages directly on
the chart.
import [Link] as plt
labels = ['Food','Rent','Travel','Other']
sizes = [40,30,20,10]
colors = ['skyblue','lightgreen','gold','salmon']
[Link](sizes, labels=labels, colors=colors,
autopct='%1.1f%%', explode=(0.05,0,0,0))
[Link]('Pie Chart')
[Link]('equal')
[Link]()
Page 8 | Matplotlib Complete Guide
Statistical & Distribution Plots
7 Box Plot
STATISTICAL & DISTRIBUTION PLOTS
WHAT IT IS
A box plot (box-and-whisker plot) summarizes a distribution using
five numbers: minimum, first quartile, median, third quartile, and
maximum, with outliers shown as individual points.
WHEN TO USE IT
Use box plots to compare the spread and central tendency of
several groups side by side, and to quickly spot outliers, without
needing to see every raw data point.
TIP
The box shows the interquartile range (middle 50% of data); the
line inside is the median. Whiskers typically extend to 1.5x the
IQR, and points beyond that are flagged as outliers.
import [Link] as plt
import numpy as np
data = [Link](40,100,20)
[Link](data, patch_artist=True,
boxprops=dict(facecolor='lightblue'))
[Link]('Box Plot')
[Link]('Values')
[Link]()
Page 9 | Matplotlib Complete Guide
8 Violin Plot
STATISTICAL & DISTRIBUTION PLOTS
WHAT IT IS
A violin plot combines a box plot with a rotated, mirrored kernel
density plot, showing the full shape of the underlying distribution
rather than only summary statistics.
WHEN TO USE IT
Use a violin plot instead of a box plot when you care about the
shape of the distribution — for example, to see whether a group's
data is bimodal (has two peaks) or skewed, which a box plot
would hide.
TIP
The width of the 'violin' at any height shows how dense the data
is there. Add showmeans=True or showmedians=True to overlay
summary statistics.
import [Link] as plt
import numpy as np
data = [[Link](70,10,100),
[Link](60,15,100)]
[Link](data, showmeans=True,
showmedians=True)
[Link]('Violin Plot')
[Link]('Groups')
[Link]('Values')
[Link]()
Page 10 | Matplotlib Complete Guide
9 Stem Plot
STATISTICAL & DISTRIBUTION PLOTS
WHAT IT IS
A stem plot draws a vertical line ('stem') from the baseline to each
data value, topped with a marker, emphasizing discrete,
individual values rather than a continuous trend.
WHEN TO USE IT
Use stem plots for discrete sequences or signals — such as
digital signal samples, sequences of impulses, or any dataset
where each individual value at each x-position matters more than
the overall shape.
TIP
Stem plots make it easy to compare the magnitude of many
individual points at a glance; customize linefmt and markerfmt to
change stem and marker styling.
import [Link] as plt
import numpy as np
x = [Link](0,11)
y = [Link](x)
[Link](x, y, linefmt='r-', markerfmt='ro',
basefmt='k-')
[Link]('Stem Plot')
[Link]('X axis')
[Link]('Y axis')
[Link]()
Page 11 | Matplotlib Complete Guide
10 Step Plot
STATISTICAL & DISTRIBUTION PLOTS
WHAT IT IS
A step plot connects points with horizontal and vertical segments
instead of diagonal lines, creating a 'staircase' shape.
WHEN TO USE IT
Use step plots to represent values that change abruptly and stay
constant between changes, such as inventory levels, discrete
state machines, or cumulative counts that jump at specific events.
TIP
The 'where' parameter ('pre', 'post', or 'mid') controls whether the
step occurs before, after, or centered on each x value — choose
based on what the value represents at that point.
import [Link] as plt
x = [1,2,3,4,5]
y = [1,2,3,4,5]
[Link](x, y, where='post', color='green')
[Link]('Step Plot')
[Link]('X axis')
[Link]('Y axis')
[Link]()
Page 12 | Matplotlib Complete Guide
11 Stack Plot
STATISTICAL & DISTRIBUTION PLOTS
WHAT IT IS
A stack plot is a variant of the area plot where multiple series are
layered on top of one another, so the total height at any point
represents the sum of all series.
WHEN TO USE IT
Use a stack plot to show how several parts contribute to a
changing whole over time — for example, revenue by product line
across months, where you care both about the total and the
composition.
TIP
Order matters: put the series with the smoothest trend on the
bottom for a cleaner look. Always include a legend since
individual bands can be hard to label directly.
import [Link] as plt
months = ['Jan','Feb','Mar','Apr','May']
p1 = [5,7,9,10,12]
p2 = [3,4,6,7,8]
p3 = [2,3,4,5,6]
[Link](months, p1, p2, p3,
labels=['Product 1','Product 2','Product 3'],
colors=['#1f77b4','#ff7f0e','#2ca02c'])
[Link]('Stack Plot')
[Link](loc='upper left')
[Link]()
Page 13 | Matplotlib Complete Guide
12 Area Plot
STATISTICAL & DISTRIBUTION PLOTS
WHAT IT IS
An area plot is a line plot with the region between the line and the
baseline filled in with color, using plt.fill_between().
WHEN TO USE IT
Use area plots to emphasize magnitude and volume beneath a
trend line — for example cumulative totals, or when you want a
single series's trend to feel more visually 'weighted' than a plain
line plot.
TIP
Set alpha for transparency so overlapping areas remain visible
when comparing multiple series on the same axes.
import [Link] as plt
x = [1,2,3,4,5]
y = [1,3,7,5,11]
plt.fill_between(x, y, color='skyblue', alpha=0.4)
[Link](x, y, color='blue')
[Link]('Area Plot')
[Link]('X axis')
[Link]('Y axis')
[Link]()
Page 14 | Matplotlib Complete Guide
13 Error Bar Plot
STATISTICAL & DISTRIBUTION PLOTS
WHAT IT IS
An error bar plot draws a marker for each data point along with a
vertical (and/or horizontal) bar representing the uncertainty or
variability around that value.
WHEN TO USE IT
Use error bars whenever you're reporting measurements with
known uncertainty — experimental results, survey data with
confidence intervals, or repeated measurements with standard
deviation — so viewers can judge how reliable each point is.
TIP
The 'capsize' parameter adds small caps to the ends of error
bars, making them easier to read; 'yerr' can be a single value or
an array of per-point uncertainties.
import [Link] as plt
import numpy as np
x = [Link](1,6)
y = [10,20,25,30,35]
yerr = [5,7,6,8,5]
[Link](x, y, yerr=yerr, fmt='o', color='blue',
capsize=5)
[Link]('Error Bar Plot')
[Link]('X axis')
[Link]('Y axis')
[Link]()
Page 15 | Matplotlib Complete Guide
Grid, Density & Field Plots
14 Heatmap (imshow)
GRID, DENSITY & FIELD PLOTS
WHAT IT IS
A heatmap displays a 2D matrix of values as a grid of colored
cells, where color intensity encodes magnitude, using
[Link]() on numeric array data.
WHEN TO USE IT
Use heatmaps to visualize matrices such as correlation tables,
confusion matrices in machine learning, or any 2D grid of
numbers where you want to spot patterns, clusters, or hotspots
through color rather than reading raw numbers.
TIP
Always add a colorbar so viewers can map color back to value,
and choose a perceptually uniform colormap like 'viridis' to avoid
misleading visual jumps.
import [Link] as plt
import numpy as np
data = [Link]([[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
[4,5,6,7,8],
[5,6,7,8,9]])
[Link](data, cmap='viridis')
[Link](label='Intensity')
[Link]('Heatmap (imshow)')
[Link]('X axis')
[Link]('Y axis')
[Link]()
Page 16 | Matplotlib Complete Guide
15 Image Plot (imshow)
GRID, DENSITY & FIELD PLOTS
WHAT IT IS
Beyond numeric matrices, imshow() can also display actual
raster images (photos, scans, generated images) by reading pixel
data directly.
WHEN TO USE IT
Use this when you need to display or annotate a real image
inside a Matplotlib figure — for example, showing model
predictions overlaid on a photo, or comparing an original and
processed image side by side.
TIP
Use [Link]('off') to hide the axis ticks/labels when displaying a
photograph, since pixel coordinates usually aren't meaningful to
the viewer.
import [Link] as plt
img = [Link]('[Link]')
[Link](img)
[Link]('Image Plot (imshow)')
[Link]('off')
[Link]()
# Note: place an image named "[Link]"
# in the same directory as your Python file.
Page 17 | Matplotlib Complete Guide
16 Contour Plot
GRID, DENSITY & FIELD PLOTS
WHAT IT IS
A contour plot draws lines that connect points of equal value
across a 2D surface defined by a function of two variables, similar
to elevation lines on a topographic map.
WHEN TO USE IT
Use contour plots to visualize a 3D surface (like a mathematical
function, temperature field, or elevation map) in 2D, focusing on
where values are equal or changing rapidly.
TIP
Increase the 'levels' parameter for more, finer contour lines; use
[Link]() to add numeric labels directly onto contour lines.
import [Link] as plt
import numpy as np
x = [Link](-3,3,100)
y = [Link](-3,3,100)
X, Y = [Link](x, y)
Z = [Link](X**2 + Y**2)
[Link](X, Y, Z, levels=20, cmap='viridis')
[Link]('Contour Plot')
[Link]('X axis')
[Link]('Y axis')
[Link]()
Page 18 | Matplotlib Complete Guide
17 Filled Contour (contourf)
GRID, DENSITY & FIELD PLOTS
WHAT IT IS
A filled contour plot is identical to a contour plot, but the space
between contour lines is filled with solid color bands instead of
leaving it blank.
WHEN TO USE IT
Use contourf instead of contour when you want the regions
between levels to be as visually obvious as the lines themselves
— for example, weather maps showing temperature or pressure
zones.
TIP
Pair with [Link]() so viewers can read the value each color
band represents; 'cmap' choice strongly affects readability,
especially for diverging data.
import [Link] as plt
import numpy as np
x = [Link](-3,3,100)
y = [Link](-3,3,100)
X, Y = [Link](x, y)
Z = [Link](X**2 + Y**2)
cf = [Link](X, Y, Z, levels=20, cmap='viridis')
[Link](cf)
[Link]('Filled Contour (contourf)')
[Link]('X axis')
[Link]('Y axis')
[Link]()
Page 19 | Matplotlib Complete Guide
18 Hexbin Plot
GRID, DENSITY & FIELD PLOTS
WHAT IT IS
A hexbin plot divides the plotting area into hexagonal cells and
colors each by how many data points fall inside it, effectively a 2D
histogram for scatter data.
WHEN TO USE IT
Use hexbin instead of a regular scatter plot when you have so
many overlapping points that a scatter plot becomes an
unreadable blob — hexbin reveals density patterns that would
otherwise be hidden.
TIP
The 'gridsize' parameter controls hexagon size — smaller values
give finer detail but noisier bins; always add a colorbar labeled
'Count'.
import [Link] as plt
import numpy as np
x = [Link](10000)
y = [Link](10000)
[Link](x, y, gridsize=30, cmap='Blues')
[Link](label='Count')
[Link]('Hexbin Plot')
[Link]('X axis')
[Link]('Y axis')
[Link]()
Page 20 | Matplotlib Complete Guide
Specialized Plots
19 Polar Plot
SPECIALIZED PLOTS
WHAT IT IS
A polar plot maps data onto a circular coordinate system using an
angle (theta) and radius (r), rather than the x/y Cartesian grid
used by most other plots.
WHEN TO USE IT
Use polar plots for directional or cyclical data — wind direction,
compass bearings, radar sweeps, or periodic functions where
angle is a natural variable.
TIP
Create polar axes with [Link](projection='polar') or [Link]();
grid rings represent radius, spokes represent angle in degrees or
radians.
import [Link] as plt
import numpy as np
theta = [Link](0, 2*[Link], 100)
r = [Link]([Link](4*theta))
[Link](theta, r, color='blue')
[Link]('Polar Plot')
[Link]()
Page 21 | Matplotlib Complete Guide
20 Quiver Plot
SPECIALIZED PLOTS
WHAT IT IS
A quiver plot draws arrows at grid positions, where each arrow's
direction and length represent a vector (u, v) at that point.
WHEN TO USE IT
Use quiver plots to visualize vector fields — wind velocity maps,
fluid flow, gradients, or force fields — where both magnitude and
direction matter at every point in space.
TIP
Scale arrow length with the 'scale' parameter if arrows overlap or
are too small; combine with a contour or heatmap in the
background for extra context.
import [Link] as plt
import numpy as np
x, y = [Link]([Link](-2,2,0.5),
[Link](-2,2,0.5))
u = -y
v = x
[Link](x, y, u, v, color='red')
[Link]('Quiver Plot')
[Link]()
Page 22 | Matplotlib Complete Guide
21 Stream Plot
SPECIALIZED PLOTS
WHAT IT IS
A stream plot draws continuous, curved lines that follow the
direction of a vector field, showing the path a particle would take
if released into the flow.
WHEN TO USE IT
Use stream plots instead of quiver plots when you want to see
smooth flow lines rather than discrete arrows — ideal for
visualizing fluid dynamics, magnetic fields, or airflow simulations.
TIP
Line density and color can be modulated by the local speed of the
field to add an extra dimension of information.
import [Link] as plt
import numpy as np
x, y = [Link]([Link](-2,2,20),
[Link](-2,2,20))
u = -y
v = x
[Link](x, y, u, v, color='blue')
[Link]('Stream Plot')
[Link]()
Page 23 | Matplotlib Complete Guide
22 Event Plot
SPECIALIZED PLOTS
WHAT IT IS
An event plot draws a series of short vertical (or horizontal) lines
marking the exact positions of discrete events along one axis,
stacked across multiple rows.
WHEN TO USE IT
Use event plots for spike trains in neuroscience, log timestamps,
or any dataset where you need to show precisely when discrete
events occurred across several categories or channels.
TIP
Multiple rows are simply passed as a list of lists; adjust
'lineoffsets' and 'linelengths' to control spacing between rows.
import [Link] as plt
positions = [[1,3,4,6,8],
[2,3,5,7,8],
[1,4,6,8,10],
[3,5,7,9]]
[Link](positions, color='blue')
[Link]('Event Plot')
[Link]('Time')
[Link]('Row')
[Link]()
Page 24 | Matplotlib Complete Guide
23 Spectrogram
SPECIALIZED PLOTS
WHAT IT IS
A spectrogram shows how the frequency content of a signal
changes over time, with time on the x-axis, frequency on the
y-axis, and color representing signal strength (power) at each
point.
WHEN TO USE IT
Use spectrograms for audio analysis, vibration analysis, or any
time-varying signal where you need to see which frequencies are
present and when — essential in speech processing and
mechanical fault detection.
TIP
'NFFT' controls frequency resolution vs. time resolution trade-off;
a colorbar labeled in dB helps interpret signal strength.
import [Link] as plt
import numpy as np
fs = 1000
t = [Link](0,1,fs)
signal = [Link](2*[Link]*50*t) + \
0.5*[Link](2*[Link]*120*t)
[Link](signal, Fs=fs, NFFT=256, cmap='plasma')
[Link]('Spectrogram')
[Link]('Time')
[Link]('Frequency (Hz)')
[Link](label='dB')
[Link]()
Page 25 | Matplotlib Complete Guide
24 Spy Plot
SPECIALIZED PLOTS
WHAT IT IS
A spy plot visualizes the sparsity pattern of a matrix, drawing a
mark wherever a matrix element is non-zero and leaving the rest
blank.
WHEN TO USE IT
Use spy plots when working with sparse matrices in scientific
computing or linear algebra to quickly see the structure and
density of non-zero entries, such as in graph adjacency matrices.
TIP
Adjust 'markersize' for large matrices so individual non-zero
points remain visible without overwhelming the plot.
import [Link] as plt
import numpy as np
from scipy import sparse
[Link](0)
A = [Link](100,100, density=0.05,
format='csr')
[Link](A, markersize=2)
[Link]('Spy Plot (Sparse Matrix)')
[Link]()
Page 26 | Matplotlib Complete Guide
25 Table
SPECIALIZED PLOTS
WHAT IT IS
Matplotlib can render an actual data table (rows, columns, cell
text) as part of a figure using [Link](), rather than plotting
numeric values graphically.
WHEN TO USE IT
Use a table when raw values themselves are the point — precise
numbers that would lose meaning if converted into bars or lines,
such as a small results summary alongside a chart.
TIP
Hide the surrounding axis with [Link]('off') since a table doesn't
need x/y ticks; use table.auto_set_font_size(False) for manual
font control.
import [Link] as plt
fig, ax = [Link]()
[Link]('off')
data = [['Alice',85,90,88],
['Bob',78,85,80],
['Charlie',92,95,93]]
columns = ['Name','Math','Physics','Chemistry']
table = [Link](cellText=data, colLabels=columns,
loc='center', cellLoc='center')
table.auto_set_font_size(False)
table.set_fontsize(10)
[Link](1,1.5)
[Link]('Table')
[Link]()
Page 27 | Matplotlib Complete Guide
3D Plots
26 3D Line Plot
3D PLOTS
WHAT IT IS
A 3D line plot extends the standard line plot into three
dimensions, tracing a path through (x, y, z) space instead of a flat
plane.
WHEN TO USE IT
Use a 3D line plot to visualize a trajectory or parametric curve in
3D space — such as a spiral, orbit path, or the path of a particle
over time with three simultaneous coordinates.
TIP
Requires importing Axes3D and creating the axes with
projection='3d'; rotate the view interactively when displayed
outside static export to explore the shape.
import [Link] as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
t = [Link](0, 4*[Link], 100)
x = [Link](t)
y = [Link](t)
z = t
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
[Link](x, y, z, color='blue')
ax.set_title('3D Line Plot')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
[Link]()
Page 28 | Matplotlib Complete Guide
27 3D Scatter Plot
3D PLOTS
WHAT IT IS
A 3D scatter plot places individual markers at (x, y, z) coordinates
in a 3D space, the three-dimensional counterpart of a standard
scatter plot.
WHEN TO USE IT
Use a 3D scatter plot when analyzing relationships between three
numeric variables simultaneously, such as clustering results in
3D feature space.
TIP
3D scatter plots can be hard to read in a static image because of
depth ambiguity — consider adding color or size to encode a
fourth variable, or provide multiple viewing angles.
import [Link] as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
[Link](0)
x = [Link](50)
y = [Link](50)
z = [Link](50)
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
[Link](x, y, z, c='red', marker='o')
ax.set_title('3D Scatter Plot')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
[Link]()
Page 29 | Matplotlib Complete Guide
28 3D Surface Plot
3D PLOTS
WHAT IT IS
A 3D surface plot renders a continuous shaded surface z = f(x, y)
over a grid, showing height and curvature with color shading and
lighting cues.
WHEN TO USE IT
Use surface plots to visualize functions of two variables,
terrain/elevation data, or optimization landscapes where you
need to see peaks, valleys, and saddle points clearly.
TIP
Choose a smooth colormap like 'viridis' and add [Link]() to
map color to height; reduce grid resolution for large datasets to
keep rendering fast.
import [Link] as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = [Link](-5,5,50)
y = [Link](-5,5,50)
X, Y = [Link](x, y)
Z = [Link]([Link](X**2 + Y**2))
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_title('3D Surface Plot')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
[Link](surf, shrink=0.5, aspect=5)
[Link]()
Page 30 | Matplotlib Complete Guide
29 3D Wireframe Plot
3D PLOTS
WHAT IT IS
A 3D wireframe plot shows the same surface as a surface plot
but draws only the grid lines, leaving the faces between them
transparent (unshaded).
WHEN TO USE IT
Use a wireframe instead of a filled surface when you want to see
through the shape to underlying data, or want a lighter-weight
rendering of a mathematical surface for quick inspection of its
structure.
TIP
Wireframes render much faster than filled surfaces for large grids
and are useful when overlaying scatter points on top of a surface
shape.
import [Link] as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = [Link](-5,5,30)
y = [Link](-5,5,30)
X, Y = [Link](x, y)
Z = [Link]([Link](X**2 + Y**2))
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X, Y, Z, color='blue')
ax.set_title('3D Wireframe Plot')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
[Link]()
Page 31 | Matplotlib Complete Guide
30 3D Bar Plot
3D PLOTS
WHAT IT IS
A 3D bar plot extends a standard bar chart into three dimensions,
drawing each bar as a 3D box positioned at (x, y) coordinates
with a height along z.
WHEN TO USE IT
Use 3D bar plots to compare values across two categorical
dimensions at once — for example sales by region and by
quarter — where a grouped 2D bar chart would become too
cluttered.
TIP
3D bar charts can be harder to read precisely than 2D grouped
bars due to perspective distortion — use them for visual impact,
but pair with a 2D chart or table if exact values matter.
import [Link] as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = [Link](4)
y = [Link](3)
X, Y = [Link](x, y)
top = [Link](1,10,(3,4))
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
ax.bar3d([Link](), [Link](), 0, 0.5, 0.5,
[Link](), shade=True)
ax.set_title('3D Bar Plot')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
[Link]()
Page 32 | Matplotlib Complete Guide