Matplotlib Functions

Matplotlib is the most widely used data visualization library in Python, supporting the creation of static, animated, and interactive charts.

This document comprehensively organizes the functions and methods of all public interfaces in Matplotlib, making it easy to quickly look up corresponding features and usage.


Two Major Programming Interfaces

Matplotlib provides two usage approaches, suitable for different scenarios.

Feature Axes Interface (Explicit/Object-Oriented) pyplot Interface (Implicit/Functional)
Usage First create Figure and Axes objects, then call object methods. Directly call pyplot module functions, implicitly operating on the current figure.
Applicable Scenarios Complex charts, multiple subplots, fine-grained control required. Quick plotting, interactive exploration, simple charts.
Code Example fig, ax = plt.subplots(); ax.plot(x, y) plt.plot(x, y); plt.title("Title")
Recommendation Level Recommended(Clearer, More Controllable) Suitable for simple scenarios and rapid prototyping.

The Axes interface is the officially recommended programming approach. The code logic is clearer and less error-prone when handling multiple subplots and complex charts. For quick reference, the following lists both pyplot functions and the corresponding Axes methods.


pyplot Module - Full Function List

pyplot is Matplotlib's top-level interface, providing a MATLAB-like plotting experience. The following lists all functions by official category.

1. Figure and Axes Management

Functions for creating and managing Figure (canvas) and Axes (coordinate system/subplot).

FunctionDescription
figure()Create a new Figure or activate an existing Figure.
subplots()RecommendedCreate a Figure and a set of Axes subplots.
subplot()Add a single subplot to the current Figure (by row and column index).
subplot2grid()Create a subplot at a specified position in a grid layout.
subplot_mosaic()Create complex non-uniform layout using label strings.
axes()Add an Axes to the current Figure.
gca()Get the current Axes object.
gcf()Get the current Figure object.
sca()Set the current Axes.
cla()Clear the current Axes.
clf()Clear the current Figure.
close()Close the Figure window.
delaxes()Remove the specified Axes from the Figure.
fignum_exists()Check whether a Figure with the specified number exists.
get_figlabels()Return the list of labels of all Figures.
get_fignums()Return the list of numbers of all Figures.
twinx()Create a twin y-axis sharing the x-axis.
twiny()Create a twin x-axis sharing the y-axis.

2. Basic Plotting

The most commonly used chart type plotting functions.

FunctionDescription
plot()Plot a line chart (most common).
scatter()Plot a scatter plot, supporting size/color/transparency mapping.
bar()Plot a vertical bar chart.
barh()Plot a horizontal bar chart.
bar_label()Add value labels to the bars of a bar chart.
grouped_bar()Plot a grouped bar chart.
pie()Plot a pie chart.
pie_label()Add labels to a pie chart.
stem()Plot a stem plot (matchstick plot).
eventplot()Plot an event plot (multiple horizontal lines marking event positions).
step()Plot a step chart.
fill()Draw filled polygons.
fill_between()Fill the area between two horizontal curves.
fill_betweenx()Fill the area between two vertical curves.
stackplot()Plot a stacked area chart.
broken_barh()Plot horizontal broken bar chart (Gantt chart style).
vlines()Draw a vertical reference line.
hlines()Draw a horizontal reference line.
errorbar()Plot a line chart with error bars.
loglog()Log-log line chart.
semilogx()Line chart with logarithmic x-axis.
semilogy()Line chart with logarithmic y-axis.
polar()Plot in polar coordinates.

3. Span Lines (Spans)

Draw horizontal and vertical reference lines and shaded regions.

FunctionDescription
axhline()Add a horizontal line spanning the Axes.
axhspan()Add a horizontal shaded band spanning the Axes.
axvline()Add a vertical line spanning the Axes.
axvspan()Add a vertical shaded band spanning the Axes.
axline()Add an infinite line passing through two points.

4. Spectral Analysis

Functions for signal processing and spectral visualization.

FunctionDescription
acorr()Plot an autocorrelation plot.
xcorr()Plot cross-correlation
angle_spectrum()Plot angle spectrum
magnitude_spectrum()Plot magnitude spectrum
phase_spectrum()Plot phase spectrum
psd()Plot power spectral density
csd()Plot cross-spectral density
cohere()Plot coherence
specgram()Plot spectrogram (time-frequency plot)

5. Statistical Charts

Functions for plotting statistical distributions.

FunctionDescription
boxplot()Plot boxplot
violinplot()Plot violin plot
ecdf()Plot empirical cumulative distribution function (ECDF)

6. Binning and Histograms

FunctionDescription
hist()Plot 1D histogram
hist2d()Plot 2D histogram
hexbin()Plot hexagonal binning plot
stairs()Plot step histogram (new version, replacing hist's step mode)

7. Contour Lines

FunctionDescription
contour()Plot contour lines
contourf()Plot filled contours
clabel()Add labels to contours

8. 2D Arrays and Images

Visualization functions for displaying 2D data, matrices, and images.

FunctionDescription
imshow()Display an image or 2D array (heatmap)
matshow()Display a matrix as an image in a new Figure
pcolor()Plot pseudocolor mesh (creates PolyCollection)
pcolormesh()Plot pseudocolor mesh (creates QuadMesh, better performance)
spy()Plot the pattern of nonzero elements of a sparse matrix
figimage()Place an image at the Figure level (not Axes)

9. Unstructured Triangular Grids

FunctionDescription
triplot()Plot an unstructured triangular grid
tripcolor()Plot pseudocolor plot on triangular grid
tricontour()Plot contour lines on triangular grid
tricontourf()Plot filled contours on triangular grid

10. Text and Annotations

FunctionDescription
text()Add text at specified coordinates in Axes
figtext()Add text at specified position in Figure
annotate()Add annotation with arrow
arrow()Add arrow
legend()Add legend in Axes
figlegend()Add legend at Figure level
table()Add table in Axes

11. Vector Fields

FunctionDescription
quiver()Plot vector field (quiver plot)
quiverkey()Add legend scale to vector field
barbs()Plot barb plot (representing wind speed and direction in meteorology)
streamplot()Plot streamlines

12. Axis Configuration

Functions for setting axis limits, ticks, labels, and scales.

FunctionDescription
title()Set Axes title
suptitle()Set Figure suptitle
xlabel()Set x-axis label
ylabel()Set y-axis label
xlim()Get or set x-axis limits
ylim()Get or set y-axis limits
xscale()Set x-axis scale (linear/log/symlog/logit...)
yscale()Set y-axis scale (linear/log/symlog/logit...)
xticks()Get or set x-axis tick positions and labels
yticks()Get or set y-axis tick positions and labels
tick_params()Adjust tick appearance (direction, color, size, label rotation, etc.)
ticklabel_format()Set tick label format (scientific notation, etc.)
locator_params()Control tick locator parameters
minorticks_on()Show minor ticks
minorticks_off()Hide minor ticks
rgrids()Get or set radial gridlines of polar plot
thetagrids()Get or set angular gridlines of polar plot
grid()Turn gridlines on or off
axis()Convenience function to get or set certain axis properties
box()Turn Axes border lines on or off
autoscale()Automatically scale axes to fit data

13. Layout

Functions for controlling subplot arrangement and spacing.

FunctionDescription
subplots_adjust()Manually adjust subplot spacing (left/right/top/bottom/wspace/hspace)
tight_layout()Automatically adjust subplot parameters for a tight layout
margins()Set or get data margins of axes
subplot_tool()Launch interactive subplot adjustment tool window

14. Colormap

Functions related to colormaps and colorbars.

FunctionDescription
colorbar()Add colorbar
clim()Set colormap data range
get_cmap()Get the colormap object with the specified name
set_cmap()Set default colormap
gci()Get the current color-mappable image object
sci()Set the current color-mappable image object
imread()Read image from file into array
imsave()Save array as image file
colormapsColormap registry object
color_sequencesColor sequence registry object

15. Configuration

Functions for managing Matplotlib global configuration parameters.

FunctionDescription
rc()Set rc parameters (can be set in batch)
rc_context()Context manager for temporarily setting rc parameters
rcdefaults()Restore all rc parameters to default values

16. Output and Interaction

Functions for controlling plot display, saving, and interaction modes.

FunctionDescription
show()Display all open Figures
savefig()Save current Figure to file
draw()Force re-render of current Figure
draw_if_interactive()Render Figure if in interactive mode
pause()Pause for the specified number of seconds (processing events during the pause)
ion()Turn on interactive mode
ioff()Turn off interactive mode
isinteractive()Return whether currently in interactive mode
install_repl_displayhook()Install REPL display hook (to display Figures automatically)
uninstall_repl_displayhook()Uninstall REPL display hook
switch_backend()Switch backend

17. Other Utility Functions

FunctionDescription
connect()Bind event callback function
disconnect()Unbind event callback function
ginput()Get coordinate points via mouse clicks
waitforbuttonpress()Wait for mouse or keyboard press, return event type
findobj()Find Artist objects matching the specified conditions
get()Get the property value of an Artist object
getp()Get the properties of an Artist object (alias of get)
setp()Set the properties of an Artist object
get_current_fig_manager()Get the window manager of the current Figure
new_figure_manager()Create a new Figure manager for the specified Figure
set_loglevel()Set the Matplotlib log level
xkcd()Switch to xkcd (hand-drawn comic) style

Axes Object - Full Method List

Axes (Axes object) represents a subplot within a Figure, containing data, ticks, labels, titles, etc. The following lists all methods completely according to the official classification.

1. Basic Plotting Methods

MethodDescription
Axes.plot()Line plot
Axes.scatter()Scatter plot
Axes.bar()Vertical bar chart
Axes.barh()Horizontal bar chart
Axes.bar_label()Add value labels on bars
Axes.grouped_bar()Grouped bar chart
Axes.pie()Pie chart
Axes.pie_label()Pie chart labels
Axes.stem()Stem plot
Axes.eventplot()Event plot
Axes.step()Step plot
Axes.fill()Fill polygons
Axes.fill_between()Horizontal fill region
Axes.fill_betweenx()Vertical fill region
Axes.stackplot()Stacked area plot
Axes.broken_barh()Horizontal broken bar chart
Axes.vlines()Vertical reference line
Axes.hlines()Horizontal reference line
Axes.errorbar()Line plot with error bars
Axes.loglog()Log-log scale
Axes.semilogx()x-axis log scale
Axes.semilogy()y-axis log scale

2. Span Line Methods

MethodDescription
Axes.axhline()Horizontal reference line
Axes.axvline()Vertical reference line
Axes.axhspan()Horizontal shaded band
Axes.axvspan()Vertical shaded band
Axes.axline()Infinite line through two points

3. Spectral Analysis Methods

MethodDescription
Axes.acorr()Autocorrelation plot
Axes.xcorr()Cross-correlation plot
Axes.angle_spectrum()Angle spectrum
Axes.magnitude_spectrum()Magnitude spectrum
Axes.phase_spectrum()Phase spectrum
Axes.psd()Power spectral density
Axes.csd()Cross spectral density
Axes.cohere()Coherence
Axes.specgram()Spectrogram (time-frequency plot)

4. Statistical Methods

MethodDescription
Axes.boxplot()Box plot
Axes.bxp()Draw a box plot from precomputed statistics
Axes.violinplot()Violin plot
Axes.violin()Draw a violin plot from precomputed statistics
Axes.ecdf()Empirical cumulative distribution function

5. Binning and Histogram Methods

MethodDescription
Axes.hist()Histogram
Axes.hist2d()2D histogram
Axes.hexbin()Hexbin plot
Axes.stairs()Stairs histogram

6. Contour Methods

MethodDescription
Axes.contour()Contour
Axes.contourf()Filled contour
Axes.clabel()Contour labels

7. 2D Array Methods

MethodDescription
Axes.imshow()Display image/heatmap
Axes.matshow()Matrix image
Axes.pcolor()Pseudocolor mesh (PolyCollection)
Axes.pcolorfast()Fast pseudocolor (drawn with imshow)
Axes.pcolormesh()Pseudocolor mesh (QuadMesh, recommended)
Axes.spy()Sparse matrix pattern

8. Unstructured Triangular Grid Methods

MethodDescription
Axes.triplot()Triangular grid lines
Axes.tripcolor()Triangular grid pseudocolor
Axes.tricontour()Triangular grid contour
Axes.tricontourf()Triangular grid filled contour

9. Text and Annotation Methods

MethodDescription
Axes.text()Add text
Axes.annotate()Add annotation with arrow
Axes.table()Add table
Axes.arrow()Add arrow
Axes.inset_axes()Create an inset axes within the Axes
Axes.indicate_inset()Mark the inset axes region on the parent Axes
Axes.indicate_inset_zoom()Mark the zoomed region of the inset axes
Axes.secondary_xaxis()Add a secondary x-axis (display the same data at another location)
Axes.secondary_yaxis()Add a secondary y-axis

10. Vector Field Methods

MethodDescription
Axes.quiver()Vector field (arrow plot)
Axes.quiverkey()Vector field legend scale bar
Axes.barbs()Wind barb plot
Axes.streamplot()Streamline plot

11. Clearing Methods

MethodDescription
Axes.cla()Clear all content in the Axes
Axes.clear()Clear the Axes (same as cla())

12. Appearance Methods

MethodDescription
Axes.axis()Set axis visibility or range
Axes.set_axis_off()Hide the axes
Axes.set_axis_on()Show the axes
Axes.set_frame_on()Show the Axes frame
Axes.get_frame_on()Get whether the frame is visible
Axes.set_axisbelow()Set whether grid/ticks are below data
Axes.get_axisbelow()Get the grid/tick layer
Axes.grid()Set grid lines
Axes.get_facecolor()Get the Axes background color
Axes.set_facecolor()Set the Axes background color

13. Property Cycling

MethodDescription
Axes.set_prop_cycle()Set the property cycle for line colors/linestyles, etc.

14. Axis and Ticks Control

Axis access:

MethodDescription
Axes.xaxis / Axes.yaxisGet the Axis object for the x/y axis (property)
Axes.get_xaxis() / get_yaxis()Get the Axis object for the x/y axis

Axis range and direction:

MethodDescription
Axes.set_xlim() / get_xlim()Set/get the x-axis range
Axes.set_ylim() / get_ylim()Set/get the y-axis range
Axes.set_xbound() / get_xbound()Set/get the lower and upper bounds of the x-axis
Axes.set_ybound() / get_ybound()Set/get the lower and upper bounds of the y-axis
Axes.invert_xaxis()Invert the x-axis direction
Axes.invert_yaxis()Invert the y-axis direction
Axes.xaxis_inverted() / yaxis_inverted()Query whether the axis is inverted
Axes.set_xinverted() / get_xinverted()Set/get whether the x-axis is inverted
Axes.set_yinverted() / get_yinverted()Set/get whether the y-axis is inverted
Axes.update_datalim()Extend the data limits with new data points

Axis labels and legend:

MethodDescription
Axes.set_xlabel() / get_xlabel()Set/get the x-axis label
Axes.set_ylabel() / get_ylabel()Set/get the y-axis label
Axes.label_outer()Keep tick labels only on the outermost subplots
Axes.set_title() / get_title()Set/get the Axes title
Axes.legend()Add a legend
Axes.get_legend()Get the current legend object
Axes.get_legend_handles_labels()Get the legend handles and labels

Axis scale:

MethodDescription
Axes.set_xscale() / get_xscale()Set/get the x-axis scale
Axes.set_yscale() / get_yscale()Set/get the y-axis scale

Autoscaling and margins:

MethodDescription
Axes.autoscale()Autoscale the view to fit the data
Axes.autoscale_view()Autoscale the view only (without changing margins)
Axes.margins()Set or get data margins
Axes.relim()Recalculate the data limits based on the current Artists
Axes.use_sticky_edges()Use sticky edges
Axes.set_xmargin() / get_xmargin()Set/get the x-axis margin
Axes.set_ymargin() / get_ymargin()Set/get the y-axis margin
Axes.set_autoscale_on() / get_autoscale_on()Set/get whether to autoscale
Axes.set_autoscalex_on() / get_autoscalex_on()Set/get whether the x-axis autoscales
Axes.set_autoscaley_on() / get_autoscaley_on()Set/get whether the y-axis autoscales

Aspect ratio:

MethodDescription
Axes.set_aspect() / get_aspect()Set/get the axes aspect ratio ('equal'/'auto'/number)
Axes.set_box_aspect() / get_box_aspect()Set/get the Axes box aspect ratio
Axes.apply_aspect()Apply the current aspect ratio setting
Axes.set_adjustable() / get_adjustable()Set/get the adjustable direction ('box'/'datalim')

Ticks and tick labels:

MethodDescription
Axes.set_xticks() / get_xticks()Set/get the x-axis tick positions
Axes.set_yticks() / get_yticks()Set/get the y-axis tick positions
Axes.set_xticklabels() / get_xticklabels()Set/get the x-axis tick labels
Axes.set_yticklabels() / get_yticklabels()Set/get the y-axis tick labels
Axes.get_xmajorticklabels()Get the x-axis major tick labels
Axes.get_xminorticklabels()Get the x-axis minor tick labels
Axes.get_ymajorticklabels()Get the y-axis major tick labels
Axes.get_yminorticklabels()Get the y-axis minor tick labels
Axes.get_xgridlines()Get the x-axis grid lines
Axes.get_ygridlines()Get the y-axis grid lines
Axes.get_xticklines()Get the x-axis tick lines
Axes.get_yticklines()Get the y-axis tick lines
Axes.xaxis_date()Set the x-axis ticks to date format
Axes.yaxis_date()Set the y-axis ticks to date format
Axes.minorticks_on()Show minor ticks
Axes.minorticks_off()Hide minor ticks
Axes.ticklabel_format()Set the tick label format
Axes.tick_params()Adjust tick appearance parameters
Axes.locator_params()Control tick locator parameters

15. Units

MethodDescription
Axes.convert_xunits()Convert x values using the unit converter
Axes.convert_yunits()Convert y values using the unit converter
Axes.have_units()Check whether a unit converter is registered

16. Adding Artists

MethodDescription
Axes.add_artist()Add an arbitrary Artist object
Axes.add_child_axes()Add a child Axes
Axes.add_collection()Add a Collection object
Axes.add_container()Add a Container object
Axes.add_image()Add an AxesImage object
Axes.add_line()Add a Line2D object
Axes.add_patch()Add a Patch object
Axes.add_table()Add a Table object

17. Twin Axes and Shared Axes

MethodDescription
Axes.twinx()Create a twin y-axis sharing the x-axis
Axes.twiny()Create a twin x-axis sharing the y-axis
Axes.sharex()Share the x-axis with other Axes
Axes.sharey()Share the y-axis with other Axes
Axes.get_shared_x_axes()Get the Grouper object for shared x-axes
Axes.get_shared_y_axes()Get the Grouper object for shared y-axes

18. Axes Position

MethodDescription
Axes.get_position() / set_position()Get/set the position and size of the Axes in the Figure
Axes.get_anchor() / set_anchor()Get/set the anchor point (fixed position) of the Axes
Axes.get_axes_locator() / set_axes_locator()Get/set the Axes locator callback function
Axes.get_subplotspec() / set_subplotspec()Get/set the SubplotSpec object
Axes.reset_position()Reset the Axes position to its original value

19. Asynchronous/Events

MethodDescription
Axes.staleMark whether the Artist needs redrawing (property)
Axes.pchanged()Notify a property change event
Axes.add_callback()Add a property change callback
Axes.remove_callback()Remove a property change callback

20. Interaction

MethodDescription
Axes.can_pan() / can_zoom()Return whether pan/zoom is enabled
Axes.set_navigate() / get_navigate()Set/get whether the navigation toolbar is active
Axes.set_navigate_mode() / get_navigate_mode()Set/get the navigation mode
Axes.start_pan() / drag_pan() / end_pan()Start/drag/end of pan operation
Axes.format_coord()Format the coordinate string displayed on the toolbar
Axes.format_cursor_data()Format the data value at the cursor
Axes.format_xdata() / format_ydata()Format x/y data values
Axes.mouseover()Determine whether the mouse is over the Axes
Axes.in_axes()Determine whether a point is inside the Axes
Axes.contains() / contains_point()Determine whether an Artist contains a point
Axes.get_cursor_data()Get the data at the cursor position
Axes.get_forward_navigation_events() / set_forward_navigation_events()Get/set navigation event forwarding

21. Child Element Querying

MethodDescription
Axes.get_children()Get all child Artists
Axes.get_images()Get all image objects
Axes.get_lines()Get all line objects
Axes.findobj()Find child Artists matching the condition

22. Drawing

MethodDescription
Axes.draw()Render the Axes
Axes.draw_artist()Draw a single Artist (low-level method)
Axes.redraw_in_frame()Redraw within the frame
Axes.get_window_extent()Get the Axes bounds in the display window
Axes.get_tightbbox()Get the tight bounding box of the Axes
Axes.get_rasterization_zorder() / set_rasterization_zorder()Get/set the zorder threshold for rasterization

23. Projection (Subclasses Should Override)

MethodDescription
Axes.nameProjection name (e.g., 'rectilinear', 'polar')
Axes.get_xaxis_transform() / get_yaxis_transform()Get the x/y axis transform
Axes.get_data_ratio()Get the data aspect ratio
Axes.get_xaxis_text1_transform()Bottom label transform of the x-axis
Axes.get_xaxis_text2_transform()Top label transform of the x-axis
Axes.get_yaxis_text1_transform()Left label transform of the y-axis
Axes.get_yaxis_text2_transform()Right label transform of the y-axis

24. Other Methods

MethodDescription
Axes.set()Batch set properties
Axes.zorderGet/set zorder (property)
Axes.get_figure()Get the parent Figure object
Axes.figureParent Figure object (property)
Axes.remove()Remove itself from the Figure
Axes.has_data()Check whether there is data
Axes.get_default_bbox_extra_artists()Get artists to additionally include in bounding box calculation
Axes.get_transformed_clip_path_and_affine()Get the transformed clipping path
Axes.viewLimView limits (property)
Axes.dataLimData limits (property)
Axes.spinesSpine dictionary (property)

Figure Object - Full Method List

Figure is the top-level container of the entire chart, managing all Axes, Artists, and layout.

1. Adding Axes and SubFigure

MethodDescription
Figure.subplots()RecommendedCreate an Axes subplot grid
Figure.add_subplot()Add a single subplot at a given row/column position
Figure.add_axes()Add an Axes at a specified position and size
Figure.subplot_mosaic()Create complex subplot arrangements using label-based layout
Figure.add_gridspec()Add a GridSpec layout object
Figure.subfigures()Create a nested SubFigure
Figure.add_subfigure()Add a single SubFigure
Figure.axesAxes list (property)
Figure.get_axes()Get all Axes
Figure.delaxes()Remove the specified Axes

2. Saving

MethodDescription
Figure.savefig()Save the Figure to a file

3. Figure-level Annotations

MethodDescription
Figure.suptitle() / get_suptitle()Set/get the Figure suptitle
Figure.supxlabel() / get_supxlabel()Set/get the Figure-level x label
Figure.supylabel() / get_supylabel()Set/get the Figure-level y label
Figure.colorbar()Add a colorbar
Figure.legend()Add a global legend
Figure.text()Add text at the Figure level
Figure.align_labels()Align axis labels of all subplots
Figure.align_xlabels()Align x-axis labels of all subplots
Figure.align_ylabels()Align y-axis labels of all subplots
Figure.align_titles()Align titles of all subplots
Figure.autofmt_xdate()Automatically rotate date tick labels

4. Figure Geometry

MethodDescription
Figure.set_size_inches() / get_size_inches()Set/get the Figure size (in inches)
Figure.set_figheight() / get_figheight()Set/get the Figure height
Figure.set_figwidth() / get_figwidth()Set/get the Figure width
Figure.dpiDPI resolution (property)
Figure.set_dpi() / get_dpi()Set/get the DPI

5. Subplot Layout

MethodDescription
Figure.subplots_adjust()Manually adjust subplot spacing
Figure.set_layout_engine()Set the layout engine ('constrained'/'compressed'/'none')
Figure.get_layout_engine()Get the current layout engine
Figure.tight_layout()Automatic tight layout (deprecated)
Figure.set_tight_layout() / get_tight_layout()Set/get tight_layout (deprecated)
Figure.set_constrained_layout() / get_constrained_layout()Set/get constrained_layout (deprecated)
Figure.set_constrained_layout_pads() / get_constrained_layout_pads()Set/get constrained_layout margins (deprecated)

6. Interaction

MethodDescription
Figure.ginput()Get coordinate points via mouse clicks
Figure.waitforbuttonpress()Wait for mouse or keyboard press
Figure.pick()Trigger a pick event
Figure.add_axobserver()Add an Axes observer

7. Appearance Modification

MethodDescription
Figure.set_frameon() / get_frameon()Set/get whether the Figure background is visible
Figure.set_linewidth() / get_linewidth()Set/get the Figure frame line width
Figure.set_facecolor() / get_facecolor()Set/get the Figure background color
Figure.set_edgecolor() / get_edgecolor()Set/get the Figure frame color

8. Adding and Getting Artists

MethodDescription
Figure.add_artist()Add an arbitrary Artist
Figure.figimage()Place an image at the Figure level
Figure.get_children()Get all child Artists

9. State Management

MethodDescription
Figure.clear()Clear the Figure
Figure.gca()Get the current Axes
Figure.sca()Set the current Axes
Figure.show()Show the Figure
Figure.draw()Render the Figure
Figure.draw_artist()Draw a single Artist
Figure.draw_without_rendering()Compute layout without rendering (to obtain size information)
Figure.set_canvas()Set the canvas
Figure.get_tightbbox()Get the tight bounding box of the Figure
Figure.get_window_extent()Get the Figure bounds in the display window

10. Helper Functions

FunctionDescription
figaspect()Calculate the Figure size based on the specified aspect ratio

SubFigure Object - Method List

SubFigure is a logical child Figure nested inside a parent Figure, with methods similar to Figure.

Adding Axes

MethodDescription
SubFigure.subplots()Create a subplot grid
SubFigure.add_subplot()Add a single subplot
SubFigure.add_axes()Add an Axes at a specified position
SubFigure.subplot_mosaic()Label-based layout subplots
SubFigure.add_gridspec()Add a GridSpec
SubFigure.subfigures()Create a deeper nested SubFigure
SubFigure.add_subfigure()Add a single SubFigure
SubFigure.delaxes()Remove Axes

Annotations

MethodDescription
SubFigure.suptitle() / get_suptitle()SubFigure suptitle
SubFigure.supxlabel() / get_supxlabel()SubFigure x label
SubFigure.supylabel() / get_supylabel()SubFigure y label
SubFigure.colorbar()Colorbar
SubFigure.legend()Legend
SubFigure.text()Text
SubFigure.align_labels()Align labels
SubFigure.align_xlabels() / align_ylabels()Align x/y labels
SubFigure.align_titles()Align titles

Artist and Appearance

MethodDescription
SubFigure.add_artist()Add an Artist
SubFigure.get_children()Get child Artists
SubFigure.set_frameon() / get_frameon()Set/get the frame
SubFigure.set_linewidth() / get_linewidth()Set/get the line width
SubFigure.set_facecolor() / get_facecolor()Set/get the background color
SubFigure.set_edgecolor() / get_edgecolor()Set/get the frame color
SubFigure.set_dpi() / get_dpi()Set/get the DPI

Style Configuration Quick Reference

Built-in Style Sheets

Byplt.style.use('name')switching styles.

Style nameDescription
defaultDefault style, clean and neutral
ggplotMimics R ggplot2 style, gray background with white grid
seaborn-v0_8Modern style similar to the seaborn library
seaborn-v0_8-brightseaborn bright palette
seaborn-v0_8-colorblindseaborn colorblind-friendly palette
seaborn-v0_8-darkseaborn dark style
seaborn-v0_8-dark-paletteseaborn deep palette
seaborn-v0_8-darkgridseaborn darkgrid style
seaborn-v0_8-deepseaborn dark palette
seaborn-v0_8-mutedseaborn muted palette
seaborn-v0_8-notebookseaborn notebook style
seaborn-v0_8-paperseaborn paper style
seaborn-v0_8-pastelseaborn pastel palette
seaborn-v0_8-posterseaborn poster style
seaborn-v0_8-talkseaborn talk style
seaborn-v0_8-ticksseaborn ticks style
seaborn-v0_8-whiteseaborn white style
seaborn-v0_8-whitegridseaborn whitegrid style
fivethirtyeightMimics FiveThirtyEight data journalism style
dark_backgroundDark background, suitable for presentations and nighttime use
bmhBayesian Methods for Hackers style
grayscaleGrayscale style, suitable for black-and-white printing
classicMatplotlib v1.x classic style
fastSimplified style, faster rendering
Solarize_Light2Solarized light theme
tableau-colorblind10Tableau colorblind-friendly palette

Common rcParams Configurations

ParametersDescriptionExample values
figure.figsizeDefault figure size (inches)[8, 6]
figure.dpiDefault resolution100
figure.facecolorFigure background color'white'
figure.edgecolorFigure edge color'white'
font.sizeGlobal font size12
font.familyFont family'sans-serif'
font.sans-serifSans-serif font list['DejaVu Sans', ...]
axes.titlesizeTitle font size'large'
axes.labelsizeAxis label font size'medium'
axes.gridWhether grid is shown by defaultFalse
axes.facecolorAxes background color'white'
axes.spines.topWhether to display the top spineTrue
axes.spines.rightWhether to display the right spineTrue
lines.linewidthDefault line width1.5
lines.markersizeDefault marker size6
lines.linestyleDefault line style'-'
legend.locLegend default location'best'
legend.fontsizeLegend font size'medium'
xtick.labelsizex-axis tick label size'medium'
ytick.labelsizey-axis tick label size'medium'
savefig.dpiDefault resolution for saving images'figure'
savefig.bboxBounding box mode when savingNone
image.cmapDefault colormap'viridis'
image.interpolationImage interpolation method'antialiased'

Colormap Quick Reference

CategoryColormap nameApplicable scenarios
Perceptually uniform (Sequential)viridis, plasma, inferno, magma, cividisContinuous data, colorblind-friendly, recommended as top choice
Sequential (single-color gradient)Greys, Purples, Blues, Greens, Oranges, Reds, YlOrBr, YlOrRd, OrRd, PuRd, RdPu, BuPu, GnBu, PuBu, YlGnBu, PuBuGn, BuGn, YlGnContinuous data from low to high, single hue
DivergingPiYG, PRGn, BrBG, PuOr, RdGy, RdBu, RdYlBu, RdYlGn, Spectral, coolwarm, bwr, seismicBidirectional data with a central reference point
Cyclictwilight, twilight_shifted, hsvPeriodic data (e.g., angles, time)
QualitativePastel1, Pastel2, Paired, Accent, Dark2, Set1, Set2, Set3, tab10, tab20, tab20b, tab20cDiscrete categorical data
Miscellaneousflag, prism, ocean, gist_earth, terrain, gist_stern, gnuplot, gnuplot2, CMRmap, cubehelix, brg, gist_rainbow, rainbow, jet, turbo, nipy_spectral, gist_ncarSpecial-purpose or visual effects

'viridis'It is the default colormap since Matplotlib 2.0, with excellent perceptual uniformity and colorblind-friendly characteristics, and is the first choice for most scenarios. Avoid using'jet'and'rainbow', which have perceptual distortion issues.


Common Examples

Example 1: Basic Line Chart and Scatter Plot

Use the explicit Axes interface to create charts with multiple curves and annotations.

Example

import matplotlib.pyplot as plt
import numpy as np

# Generate data: 100 equally spaced points between 0 and 10
x = np.linspace(0, 10, 100)
y1 = np.sin(x)   # Sine function
y2 = np.cos(x)   # Cosine function

# Create Figure and Axes (explicit interface, recommended)
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')

# Plot two lines, set colors, line styles, and labels
ax.plot(x, y1, label='sin(x)', color='blue', linewidth=2)
ax.plot(x, y2, label='cos(x)', color='red', linestyle='--', linewidth=2)

# Add highlighted scatter points at the peak positions
peak_idx_sin = np.argmax(y1)
peak_idx_cos = np.argmax(y2)
ax.scatter(x[peak_idx_sin], y1[peak_idx_sin],
           color='blue', s=100, zorder=5)
ax.scatter(x[peak_idx_cos], y2[peak_idx_cos],
           color='red', s=100, zorder=5)

# Decorate: title, axis labels, legend, grid
ax.set_title('Sine and Cosine Functions', fontsize=14)
ax.set_xlabel('x (radians)')
ax.set_ylabel('Amplitude')
ax.legend(loc='upper right')
ax.grid(True, alpha=0.3)

plt.show()
print("example: plot displayed successfully")

Example 2: Multiple Subplot Layout (2x2)

Demonstrate how to create different types of subplots in one Figure.

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)

# Create a 2x2 subplot (object-oriented interface)
fig, axes = plt.subplots(2, 2, figsize=(10, 8), layout='constrained')
fig.suptitle('Multi-panel EXAMPLE Demo', fontsize=16)

# Subplot (0,0): line plot
axes[0, 0].plot(x, np.sin(x), color='tab:blue', linewidth=2)
axes[0, 0].set_title('Line Plot')
axes[0, 0].set_ylabel('sin(x)')

# Subplot (0,1): scatter plot
np.random.seed(42)
colors = np.random.rand(50)
sizes = np.random.rand(50) * 200
axes[0, 1].scatter(np.random.rand(50), np.random.rand(50),
                   c=colors, s=sizes, alpha=0.6, cmap='viridis')
axes[0, 1].set_title('Scatter Plot')

# Subplot (1,0): bar chart (with value labels)
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]
bars = axes[1, 0].bar(categories, values,
                       color='tab:green', edgecolor='white')
axes[1, 0].bar_label(bars)  # Display values on the bars
axes[1, 0].set_title('Bar Chart')

# Subplot (1,1): histogram
data = np.random.randn(1000)
axes[1, 1].hist(data, bins=30, color='tab:orange',
                edgecolor='white', alpha=0.8)
axes[1, 1].axvline(x=0, color='red', linestyle='--', linewidth=2)
axes[1, 1].set_title('Histogram')

plt.show()

Example 3: Heatmap vs Contour Plot Comparison

Demonstrate visualizing 2D data in the same Figure using imshow and contourf.

Example

import matplotlib.pyplot as plt
import numpy as np

# Create 2D grid data
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)  # 2D function values

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5),
                                layout='constrained')

# Left panel: heatmap (imshow)
im = ax1.imshow(Z, extent=[-3, 3, -3, 3], origin='lower',
                cmap='viridis', aspect='auto')
ax1.set_title('Heatmap (imshow)', fontsize=14)
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
fig.colorbar(im, ax=ax1, label='Amplitude', shrink=0.8)

# Right panel: filled contour (contourf)
contour = ax2.contourf(X, Y, Z, levels=15, cmap='RdYlBu')
# Overlay contour boundaries
ax2.contour(X, Y, Z, levels=15, colors='black', linewidths=0.5)
ax2.set_title('Filled Contour (contourf)', fontsize=14)
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
fig.colorbar(contour, ax=ax2, label='Amplitude', shrink=0.8)

plt.show()

Example 4: Style Switching and Saving Figures

Use style sheets and rcParams to customize appearance, and save high-quality figures.

Example

import matplotlib.pyplot as plt
import numpy as np

# Use the ggplot style, then fine-tune some parameters
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = [8, 6]
plt.rcParams['font.size'] = 12

x = np.linspace(0, 10, 50)
y1 = np.exp(-x/3) * np.sin(2 * x)  # Damped sine wave
y2 = np.exp(-x/3) * np.cos(2 * x)  # Damped cosine wave

fig, ax = plt.subplots()
ax.plot(x, y1, 'o-', label='Damped sin', markersize=6)
ax.plot(x, y2, 's--', label='Damped cos', markersize=6)

# Annotate the first peak
peak_idx = np.argmax(y1)
ax.annotate(f'Peak: {y1[peak_idx]:.2f}',
            xy=(x[peak_idx], y1[peak_idx]),
            xytext=(x[peak_idx] + 1.5, y1[peak_idx] + 0.15),
            arrowprops=dict(arrowstyle='->', color='gray'),
            fontsize=10)

ax.set_title('Damped Oscillation', fontsize=16)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
ax.legend()
ax.grid(True)

# Save as a 300 DPI high-quality PNG
fig.savefig('example_damped_oscillation.png',
            dpi=300, bbox_inches='tight')
print("example: figure saved successfully")

plt.show()

Example 5: Complex Mosaic Layout

Use subplot_mosaic to create non-uniform subplot arrangements.

Example

import matplotlib.pyplot as plt
import numpy as np

# Define layout with a mosaic string:
# 'A' spans the full top row, 'B' and 'C' are at bottom-left and middle-left, 'D' occupies the bottom-right vertically
layout = """
A A A
B C D
"""


fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
                                layout='constrained')
fig.suptitle('Complex Mosaic Layout (EXAMPLE)', fontsize=16)

# Panel A: line plot (spans the top)
x = np.linspace(0, 10, 100)
axes['A'].plot(x, np.sin(x), label='sin(x)')
axes['A'].plot(x, np.cos(x), label='cos(x)')
axes['A'].set_title('Panel A: Line Plot')
axes['A'].legend()

# Panel B: pie chart
sizes = [30, 25, 20, 15, 10]
labels = ['Python', 'Java', 'C++', 'Rust', 'Go']
axes['B'].pie(sizes, labels=labels, autopct='%1.1f%%',
              startangle=90)
axes['B'].set_title('Panel B: Pie Chart')

# Panel C: bar chart
axes['C'].bar(['X', 'Y', 'Z'], [10, 25, 15],
              color=['#ff6b6b', '#4ecdc4', '#45b7d1'])
axes['C'].set_title('Panel C: Bar Chart')

# Panel D: heatmap
matrix = np.random.rand(5, 5)
im = axes['D'].imshow(matrix, cmap='Blues', aspect='auto')
axes['D'].set_title('Panel D: Heatmap')
fig.colorbar(im, ax=axes['D'])

plt.show()

Example 6: Twin Y-Axes and Inset Subplots

Demonstrate the usage of secondary_axis, twinx, and inset_axes.

Example

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')

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

# Main plot: draw two curves with different dimensions
ax.plot(x, np.sin(x), 'b-', label='sin(x) [amplitude]')
ax.set_xlabel('x (radians)')
ax.set_ylabel('sin(x)', color='blue')
ax.tick_params(axis='y', labelcolor='blue')

# Create twin y-axes (shared x-axis)
ax2 = ax.twinx()
ax2.plot(x, np.exp(x/5), 'r--', label='exp(x/5) [growth]')
ax2.set_ylabel('exp(x/5)', color='red')
ax2.tick_params(axis='y', labelcolor='red')

# Add an inset subplot in ax (zoom into a local region)
axins = ax.inset_axes([0.15, 0.5, 0.3, 0.35])
axins.plot(x, np.sin(x), 'b-')
axins.set_xlim(3, 5)
axins.set_ylim(-1.2, 1.2)
axins.set_title('Zoomed Region')
axins.grid(True, alpha=0.3)

# Mark the inset region on the main plot
ax.indicate_inset_zoom(axins, edgecolor='gray')

ax.set_title('Dual Y-Axes with Inset Zoom', fontsize=14)
plt.show()

Common Issues

Charts Not Displaying

Confirm whether you have calledplt.show()。

Under non-interactive backends (such as Agg), it must be called explicitlyshow()。

In Jupyter Notebook, use%matplotlib inlinemagic command to ensure charts are displayed inline

Too Many Ticks or Wrong Order

A common cause is passing a list of strings as data (instead of numeric or datetime values)

Matplotlib treats a list of strings as categorical variables, with one tick per unique value, arranged in order of appearance

Solution: convert the strings to numeric values, such asnp.asarray(data, dtype='float')ornp.asarray(data, dtype='datetime64[s]')。

Chinese Characters Display as Boxes

Matplotlib's default font (DejaVu Sans) does not contain Chinese glyphs; you need to specify a font that supports Chinese

Setplt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', ...]And ensure that the corresponding font is installed on the system

Labels Overlapping or Truncated

It is recommended to use when creating a Figurelayout='constrained'orlayout='compressed'parameter, which automatically handles overlapping of labels, titles, and legends

You can also usefig.tight_layout()orfig.subplots_adjust()manually adjust

Difference Between pcolor and pcolormesh

pcolor()Creates a PolyCollection, rendering is slower but more precise

pcolormesh()Creates a QuadMesh, rendering is faster, and it is the recommended choice for most scenarios

For very large grids,pcolorfast()using imshow to plot is fastest but has the lowest precision


Related Resources

  • Matplotlib official website: matplotlib.org
  • Official gallery (Gallery): matplotlib.org/stable/gallery/index.html
  • Full API reference: matplotlib.org/stable/api/index.html
  • Installation guide: matplotlib.org/stable/install/index.html
  • Contribution guide: matplotlib.org/stable/devel/index.html
Other extensions