matplotlib Cheat Sheet
matplotlib Cheat Sheet
owever, I can provide you with astructured and significantlyexpanded cheat sheetthat
H
aims to cover:
1. T he most commonly used and important methodsfrompyplot, Figure, and Axes
objects.
2. More detailed explanations and examplesfor advancedconcepts.
3. A guide on how to explorethe library further to findspecific methods you might need.
his will give you a very strong foundation and cover almost all practical use cases, while also
T
teaching you how to delve deeper into the library's capabilities.
Core Principle:
● m atplotlib.pyplot (aliased as plt): Provides a state-based interface for quick and simple
plotting. It manages the current figure and axes for you.
● Object-Oriented (OO) Interface:Directly manipulatesFigure objects (fig) and Axes
objects (ax). This is the recommended approach for complex or production-quality plots,
as it offers granular control.
Import Convention:
Python
importmatplotlib.pyplotasplt
importnumpyasnp# Essential for data generation
Part 1: matplotlib.pyplot (plt) - The Quick and Easy Interface
his module provides functions that implicitly create figures and axes and manage the current
T
state. Great for rapid prototyping.
lt.errorbar(x, y, yerr=...,
p rror Bar Plot:Plots x, y
E lt.errorbar(x_data, y_data,
p
xerr=..., ...) with error bars. yerr=y_errors, fmt='-o')
lt.figure(figsize=(w, h),
p reates a new figure.
C lt.figure(figsize=(8, 6),
p
dpi=..., ...) figsize is in inches. dpi=100,
facecolor='lightgray')
lt.subplot(nrows, ncols,
p reates a single subplot
C lt.subplot(2, 1, 1) (top plot
p
index, ...) within a grid. of 2)
lt.subplots(nrows=1,
p ecommended:Creates a
R g, ax = plt.subplots() <br>
fi
ncols=1, ...) figure and a grid of fig, axs = plt.subplots(2, 2)
subplots (returns fig, axes).
lt.savefig(fname, dpi=...,
p aves the current figure to
S lt.savefig('my_plot.pdf',
p
...) a file. dpi=300,
bbox_inches='tight')
Python
importmatplotlib.pyplotasplt
importnumpyasnp
# Data
x = np.linspace(0,2* np.pi,400)
y_sin = np.sin(x)
y_cos = np.cos(x)
y_random = np.random.rand(400) *0.5-0.25# Smallnoise
# Customize plot
plt.title("Trigonometric Functions with Random Measurements",fontsize=18, fontweight='bold')
lt.xlabel("Angle (radians)", fontsize=14)
p
plt.ylabel("Amplitude", fontsize=14)
plt.grid(True, linestyle=':', alpha=0.7)
plt.legend(loc='upper right', shadow=True, fontsize=12)
plt.xlim(0,2* np.pi)
plt.ylim(-1.5,1.5)
Python
g.add_axes([left, bottom,
fi dds an Axes at an
A x_inset =
a
width, height]) arbitrary position fig.add_axes([0.6, 0.6,
(normalized coordinates 0.25, 0.25])
from 0 to 1).
g.colorbar(mappable,
fi reates a colorbar.
C bar = fig.colorbar(im,
c
ax=..., ...) mappable is often returned ax=ax, label='Intensity')
by functions like imshow,
scatter.
fig.set_size_inches(w, h) ets the figure size in
S fig.set_size_inches(12, 7)
inches.
x.set_xticklabels(labels,
a Sets the x-axis tick labels. x.set_xticklabels(['Mon',
a
...) 'Tue', 'Wed'])
x.spines[position].set_visi
a ontrols visibility of plot
C x.spines['right'].set_visible
a
ble(bool) borders. (False)
x.spines[position].set_col
a Sets color of plot borders. x.spines['left'].set_color('b
a
or(color) lue')
x.tick_params(which='bot
a Control tick mark direction. x.tick_params(which='maj
a
h', direction='inout') or', length=7, width=2)
x.set_aspect('auto'/'equal'
a Sets the aspect ratio. x.set_aspect('equal',
a
/'num') adjustable='box')
Python
importmatplotlib.pyplotasplt
importnumpyasnp
# Data
x _common = np.linspace(0,10,100)
y1 = np.sin(x_common)
y2 = np.cos(x_common) *0.5
y3 = x_common + np.random.randn(100) *2
y4_hist = np.random.normal(0,1,1000)
y5_scatter_x = np.random.rand(50) *10
y5_scatter_y = np.random.rand(50) *5
y5_scatter_c = np.random.rand(50)
# --- Plot 2: Top-Right (Scatter Plot with Colorbar & TwinX) ---
scatter = axs[0,1] .scatter(y5_scatter_x, y5_scatter_y,c=y5_scatter_c, cmap='viridis', s=80,
lpha=0.8, edgecolor='k')
a
axs[0,1] .set_title('Data Points with Intensity',fontsize=14)
axs[0,1] .set_xlabel('Feature 1')
axs[0,1] .set_ylabel('Feature 2')
fig.colorbar(scatter, ax=axs[0,1], label='IntensityScale', shrink=0.7)
# --- Plot 4: Bottom-Right (Line Plot with Fill Between & Inset) ---
line, = axs[1,1].plot(x_common, y3, color='teal',label='Noisy Data')
axs[1,1].fill_between(x_common, y3 -2, y3 +2, color='teal',alpha=0.2, label='Confidence
Interval')
axs[1,1].set_title('Noisy Data with CI', fontsize=14)
axs[1,1].set_xlabel('Index')
xs[1,1].set_ylabel('Measurement')
a
axs[1,1].legend()
plt.show()
Python
line, = ax.plot(x, y)# Notice the comma to unpackthe list returned by plot
line.set_color('red')
line.set_linewidth(3)
line.set_linestyle('--')
Python
Python
defonclick(event):
print(f'Button{event.button}clicked at datacoords: ({event.xdata:.2f},{event.ydata:.2f})')
g, ax = plt.subplots()
fi
ax.plot(np.random.rand(10))
fig.canvas.mpl_connect('button_press_event', onclick)# Connect event
plt.show()
● 'button_press_event'
● 'motion_notify_event'
● 'key_press_event'
● 'scroll_event'
. Transforms
6
Understanding how data coordinates are transformed to display coordinates.
● ax.transData: Data coordinates.
● ax.transAxes: Axes coordinates (0,0 to 1,1 within the axes bounding box).
● fig.transFigure: Figure coordinates (0,0 to 1,1 within the figure bounding box).
. Stylesheets (plt.style.use())
7
Quickly change the aesthetic of your plots.
Python
. Animations (matplotlib.animation)
8
Create dynamic plots.
Python
frommatplotlib.animationimportFuncAnimation
g, ax = plt.subplots()
fi
x_data, y_data = [], []
line, = ax.plot([], [],'r-')
definit():
x.set_xlim(0,2* np.pi)
a
ax.set_ylim(-1.1,1.1)
returnline,
defupdate(frame):
x _data.append(frame)
y_data.append(np.sin(frame))
line.set_data(x_data, y_data)
returnline,
. Custom Colormaps
9
Define your own colormaps using LinearSegmentedColormap.from_list()1 or ListedColormap.
Python
frommatplotlib.colorsimportLinearSegmentedColormap
olors = ["red","orange","yellow","green","blue"]# Define colors
c
my_cmap = LinearSegmentedColormap.from_list("mycmap",colors)
plt.imshow(np.random.rand(10,10), cmap=my_cmap)
plt.colorbar()
plt.show()
his expanded cheat sheet should provide a strong foundation for both basic and advanced
T
Matplotlib usage. Remember that practice is key to mastering this powerful visualization
library!
You're asking for a very comprehensive list of Matplotlib methods, covering basic to advanced
topics! Matplotlib is vast, with many methods belonging to different objects like
matplotlib.pyplot, Figure, Axes, Axis, Line2D, Text, etc.
Instead of an exhaustive, unreadable list ofeverysingle method(which would be thousands
and not practical for a cheat sheet), I'll organize this into common tasks and concepts,
highlighting the most frequently used and important methods for each. I'll focus on the
Object-Oriented (OO) interface, as it provides more control and is generally recommended for
serious plotting.
This will serve as a much more useful and actionable cheat sheet.
Examples:
Python
importmatplotlib.pyplotasplt
importnumpyasnp
xs[1,1].scatter(np.random.rand(20), np.random.rand(20))
a
axs[1,1].set_title("Scatter Plot")
x_main.plot(np.linspace(0,10,100), np.sin(np.linspace(0,10,100)) +
a
np.random.randn(100)*0.1)
ax_main.set_title("Main Plot")
plt.show()
Examples:
Python
g, ax = plt.subplots()
fi
ax.plot([1,2,3] , [1,4,9])
ax.set_title("Plot to Save")
plt.savefig('my_line_plot.png', dpi=300, bbox_inches='tight')
plt.savefig('my_line_plot.pdf')
plt.show()# Display after saving if desired
plt.close(fig)# Close this specific figure
Example:
Python
Example:
Python
g, ax = plt.subplots()
fi
x = np.linspace(0,10,100)
y1 = np.sin(x)
y2 = np.cos(x)
ax.plot(x, y1, label='Sine', color='blue', linestyle='-',linewidth=2)
ax.plot(x, y2, label='Cosine', color='red', linestyle='--',marker='o', markersize=4)
ax.set_title("Line Plots with Customization")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.legend()
plt.show()
2. Scatter Plots
● a
x.scatter(x, y, s=None, c=None, marker=None, cmap=None, alpha=None,
edgecolors=None, **kwargs): Creates a scatter plot.
○ s: Marker size (can be a single value or an array).
○ c: Marker color (can be a single value or an array for colormapping).
○ cmap: Colormap to use if c is an array.
○ edgecolors: Color of the marker edges.
Example:
Python
g, ax = plt.subplots()
fi
np.random.seed(42)
x_data = np.random.rand(50) *10
y_data = np.random.rand(50) *10
sizes = np.random.rand(50) *800+50# Varying sizes
colors = np.random.rand(50)# Varying colors
Example:
Python
4. Histograms
● a
x.hist(x, bins=10, range=None, density=False, cumulative=False, histtype='bar',
align='mid', orientation='vertical', rwidth=None, log=False, **kwargs): Plots a histogram.
○ bins: Number of bins or a sequence defining bin edges.
○ density: If True, normalize to form a probability density.
○ histtype: 'bar', 'barstacked', 'step', 'stepfilled'.
○ edgecolor: Color of bin edges.
Example:
Python
g, ax = plt.subplots(figsize=(8,5) )
fi
data = np.random.normal(loc=0, scale=1, size=1000)# Normally distributed data
ax.hist(data, bins=50, color='teal', edgecolor='black',alpha=0.7, density=True)
ax.set_title("Histogram of Normal Distribution")
x.set_xlabel("Value")
a
ax.set_ylabel("Probability Density")
plt.show()
Example:
Python
g, ax = plt.subplots(figsize=(7,7) )
fi
sizes = [15,30,45,10]
labels = ['East','West','North','South']
explode = (0,0.1,0,0) # Explode the 'West' slice
Example:
Python
g, ax = plt.subplots(figsize=(8,6))
fi
x = np.array([1,2,3,4,5])
y = np.array([2,3,5,4,6])
ax.plot(x, y,'bo-')
ax.set_title("Sales Data (2024)", loc='left', fontsize=16,color='darkgreen')
ax.set_xlabel("Month", fontsize=12, color='gray')
ax.set_ylabel("Sales (Units)", fontsize=12, color='gray')
2. Legends
● a
x.legend(*args, **kwargs): Places a legend on the Axes.
○ loc: Location (e.g., 'upper right', 'lower left', 'best', (x, y) tuple).
○ fontsize: Font size of legend text.
○ frameon: Whether to draw a frame around the legend.
○ shadow: Add a shadow to the legend box.
○ ncol: Number of columns in the legend.
○ title: Title for the legend.
Example:
Python
g, ax = plt.subplots()
fi
x = np.linspace(0,5,20)
ax.plot(x, x**2, label='Quadratic', color='orange')
ax.plot(x, x**3, label='Cubic', color='green', linestyle=':')
ax.legend(loc='upper left', fontsize='small', frameon=True,shadow=True, ncol=1, title='Functions')
plt.show()
Example:
Python
g, ax = plt.subplots(figsize=(8,5) )
fi
x = np.linspace(1,100,50)
= np.log(x)
y
ax.plot(x, y)
ax.set_xscale('log')# Logarithmic x-axis
ax.set_title("Logarithmic Scale Example")
ax.set_xlabel("Values (log scale)")
ax.set_ylabel("Log(Values)")
Example:
Python
g, ax = plt.subplots(figsize=(7,5) )
fi
ax.plot(np.random.rand(10))
ax.grid(True, which='both', axis='both', linestyle=':',color='lightgray', alpha=0.8)# Grid
ax.spines['right'].set_visible(False)# Remove rightspine
ax.spines['top'].set_visible(False) # Remove topspine
ax.spines['left'].set_linewidth(1.5)
ax.spines['bottom'].set_linewidth(1.5)
ax.set_title("Grid and Spines Customization")
plt.show()
Python
g, ax = plt.subplots(figsize=(6,4) )
fi
fig.set_facecolor('#F0F0F0')# Light grey for figure
ax.set_facecolor('#E0F7FA') # Light blue for axes
ax.plot([1,2,3] , [4,5,6], color='darkblue')
ax.set_title("Custom Background Colors")
plt.show()
Example:
Python
g, ax = plt.subplots(figsize=(8,6))
fi
x = np.random.rand(100) *10
y = np.random.rand(100) *10
values = x + y + np.random.randn(100) *5
Example:
Python
fromscipy.statsimportmultivariate_normal
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12,5))
# Heatmap
im = ax1.imshow(z_data, cmap='hot', origin='lower',extent=[-2,2, -2,2] )
ax1.set_title("Heatmap")
fig.colorbar(im, ax=ax1)
# Contour Plot
ontour = ax2.contour(x_mesh, y_mesh, z_data, levels=10,colors='black', linewidths=0.8)
c
ax2.contourf(x_mesh, y_mesh, z_data, levels=10, cmap='Blues',alpha=0.7)
ax2.clabel(contour, inline=1, fontsize=8)# Add labelsto contour lines
ax2.set_title("Contour Plot")
lt.tight_layout()
p
plt.show()
Example:
Python
frommpl_toolkits.mplot3dimportAxes3D
g = plt.figure(figsize=(10,7))
fi
ax = fig.add_subplot(111, projection='3d')
Python
x = np.linspace(0,10,50)
data1 = np.exp(x/2) # Exponential growth
data2 = x *10 # Linear growth
olor1 ='tab:red'
c
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Temperature (°C)', color=color1)
ax1.plot(x, data1, color=color1, label='Temperature')
ax1.tick_params(axis='y', labelcolor=color1)
lt.tight_layout()
p
plt.show()
5. Animations
● m atplotlib.animation.FuncAnimation: Creates an animation by repeatedly calling a
function.
● matplotlib.animation.ArtistAnimation: Creates an animation using a fixed set of Artist
objects.
frommatplotlib.animationimportFuncAnimation
g, ax = plt.subplots(figsize=(7,5) )
fi
xdata, ydata = [], []
ln, = ax.plot([], [],'r-')
definit():
x.set_xlim(0,2* np.pi)
a
ax.set_ylim(-1.1,1.1)
returnln,
defupdate(frame):
x data.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
returnln,
plt.show()
Python
defonclick(event):
ifevent.xdataisnotNoneandevent.ydataisnotNone:
rint(f"Clicked at: x={event.xdata:.2f}, y={event.ydata:.2f}")
p
ax.plot(event.xdata, event.ydata,'ro', markersize=8)
fig.canvas.draw_idle()# Redraw the figure
g, ax = plt.subplots(figsize=(7,5) )
fi
ax.set_title("Click anywhere to add a red point")
cid = fig.canvas.mpl_connect('button_press_event',onclick)
plt.show()
# To disconnect: fig.canvas.mpl_disconnect(cid)
. Custom Projections
7
Matplotlib allows for custom projections beyond standard 2D and 3D. This is a very advanced
topic, involving creating custom Projection classes. Common examples include polar plots
(which are built-in) and various geographical map projections.
● fig.add_subplot(projection='polar'): Creates a polar plot Axes.
Python
g = plt.figure(figsize=(7,7))
fi
ax = fig.add_subplot(111, projection='polar')
r = np.arange(0,2,0.01)
theta =2* np.pi * r
Example:
Python
g, ax = plt.subplots(figsize=(6,4) )
fi
ax.plot([1,2,3] , [4,5,6])# This line will begreen and thicker
ax.set_title("Custom RCParams Example")
plt.show()
his extended cheat sheet covers a broad range of Matplotlib methods and advanced topics,
T
focusing on practical usage with examples. Remember that the official Matplotlib
documentation is always the most authoritative and detailed resource for any specific method
or advanced concept. Happy plotting!
ources
S
1.https://github.com/dragontree101/TensorFlow-study-cn
2.https://www.yzktw.com.cn/post/1227619.html
3.http://www.mynw.cn/cloud/15213.html
4.https://github.com/alexdumitriu/AstroStuff
5.https://github.com/ddemetriou21/python-data-handling