Matplotlib Reference Documentation

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 their functionality and usage.


Two Major Programming Interfaces

Matplotlib provides two usage styles suited to different scenarios.

Feature Axes Interface (Explicit/Object-Oriented) pyplot Interface (Implicit/Functional)
Usage Create Figure and Axes objects first, then call their methods Directly call pyplot module functions to implicitly operate on the current figure
Applicable Scenarios Complex charts, multiple subplots, fine-grained control needed 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 and more controllable) Suitable for simple scenarios and rapid prototyping

The Axes interface is the officially recommended programming style. Its 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 their corresponding Axes methods.

FunctionRelated Content
Matplotlib plot() Functionplot()
Matplotlib scatter() Functionscatter()
Matplotlib bar() / barh() Functionbar(), barh(), bar_label(), grouped_bar()
Matplotlib hist() Functionhist()
Matplotlib pie() Functionpie(), pie_label()
Matplotlib imshow() Functionimshow()
Matplotlib subplots() Functionsubplots()
Matplotlib figure() Functionfigure()
Matplotlib savefig() Functionsavefig()
Matplotlib errorbar() Functionerrorbar()
Matplotlib boxplot() Functionboxplot()
Matplotlib contour() / contourf() Functioncontour(), contourf(), clabel()
Matplotlib fill_between() / fill_betweenx() Functionfill_between(), fill_betweenx()
Matplotlib legend() Functionlegend()
Matplotlib text() / annotate() Functiontext(), annotate()
Matplotlib Title and Label Functionstitle(), xlabel(), ylabel(), suptitle(), supxlabel(), supylabel()
Matplotlib colorbar() Functioncolorbar()
Matplotlib Figure and Axes Management Functionsaxes(), cla(), clf(), close(), delaxes(), fignum_exists(), gca(), gcf(), get_figlabels(), get_fignums(), sca(), subplot(), subplot2grid(), subplot_mosaic(), twinx(), twiny()
Matplotlib Advanced Plotting Functionsstep(), stem(), eventplot(), stackplot(), broken_barh(), vlines(), hlines(), fill(), loglog(), semilogx(), semilogy()
Matplotlib Span and Vector Field Functionsaxhline(), axhspan(), axvline(), axvspan(), axline(), quiver(), quiverkey(), barbs(), streamplot()
Matplotlib Spectral Analysis Functionsacorr(), xcorr(), psd(), csd(), specgram(), cohere(), angle_spectrum(), magnitude_spectrum(), phase_spectrum()
Matplotlib 2D Data and Statistical Plot Functionshist2d(), hexbin(), stairs(), matshow(), pcolor(), pcolormesh(), spy(), figimage(), ecdf(), violinplot()
Matplotlib Triangulation and Polar Coordinate Functionstriplot(), tripcolor(), tricontour(), tricontourf(), polar(), rgrids(), thetagrids()
Matplotlib Axis Configuration Functionsxlim(), ylim(), xscale(), yscale(), xticks(), yticks(), tick_params(), ticklabel_format(), locator_params(), minorticks_on(), minorticks_off(), grid(), axis(), box(), autoscale()
Matplotlib Layout and Configuration Functionssubplots_adjust(), tight_layout(), margins(), subplot_tool(), rc(), rc_context(), rcdefaults(), clim(), get_cmap(), set_cmap(), gci(), sci(), imread(), imsave(), draw(), ion(), ioff(), pause(), switch_backend(), show(), isinteractive(), install_repl_displayhook(), uninstall_repl_displayhook(), draw_if_interactive()
Matplotlib Utility and Interaction Functionsconnect(), disconnect(), ginput(), waitforbuttonpress(), findobj(), get(), setp(), getp(), get_current_fig_manager(), new_figure_manager(), set_loglevel(), xkcd()
Matplotlib Figure-level Text and Annotation Functionsfigtext(), figlegend(), table(), arrow()

pyplot Module - Complete Function List

pyplot is the top-level interface of Matplotlib, providing a MATLAB-like plotting experience. Below are all functions listed according to the official categorization.

1. Figure and Axes Management

Functions for creating and managing Figures (canvas) and Axes (coordinate systems/subplots).

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 layouts 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 Figure windows
delaxes()Remove a 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 dual y-axes sharing the x-axis
twiny()Create dual x-axes sharing the y-axis

2. Basic Plotting

The most commonly used plotting functions for chart types.

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

3. Spans

Draw horizontal and vertical reference lines and shaded regions.

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

4. Spectral Analysis

Functions for signal processing and spectral visualization.

FunctionDescription
acorr()Plot autocorrelation
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 Plots

Plot charts related to statistical distributions.

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

6. Binning and Histograms

FunctionDescription
hist()Draw one-dimensional histogram
hist2d()Draw two-dimensional histogram
hexbin()Draw hexbin plot
stairs()Draw step histogram (new version, replaces the step mode of hist)

7. Contours

FunctionDescription
contour()Draw contour lines
contourf()Draw 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()Draw pseudocolor mesh (creates PolyCollection)
pcolormesh()Draw pseudocolor mesh (creates QuadMesh, better performance)
spy()Draw the pattern of nonzero elements of a sparse matrix
figimage()Place an image at the Figure level (not the Axes)

9. Unstructured Triangular Grids

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

10. Text and Annotations

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

11. Vector Fields

FunctionDescription
quiver()Draw a vector field (quiver plot)
quiverkey()Add a legend key to a vector field
barbs()Draw a barb plot (indicating wind speed and direction in meteorology)
streamplot()Draw a streamline plot

12. Axis Configuration

Functions to set axis limits, ticks, labels, and scales.

FunctionDescription
title()Set the Axes title
suptitle()Set the overall Figure title
xlabel()Set the x-axis label
ylabel()Set the y-axis label
xlim()Get or set the x-axis range
ylim()Get or set the y-axis range
xscale()Set the x-axis scale (linear/log/symlog/logit...)
yscale()Set the 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 the format of tick labels (scientific notation, etc.)
locator_params()Control tick locator parameters
minorticks_on()Show minor ticks
minorticks_off()Hide minor ticks
rgrids()Get or set the radial gridlines of a polar plot
thetagrids()Get or set the angular gridlines of a polar plot
grid()Turn gridlines on or off
axis()Convenience function to get or set certain axis properties
box()Turn Axes spines on or off
autoscale()Automatically scale the axes to fit the data

13. Layout

Functions to control subplot arrangement and spacing.

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

14. Colormap

Functions related to colormaps and colorbars.

FunctionDescription
colorbar()Add a colorbar
clim()Set the data range of the colormap
get_cmap()Get a colormap object by the specified name
set_cmap()Set the default colormap
gci()Get the current color-mappable image object
sci()Set the current color-mappable image object
imread()Read an image from a file into an array
imsave()Save an array as an 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 to control figure display, saving, and interaction modes.

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

17. Other Utility Functions

FunctionDescription
connect()Bind an event callback function
disconnect()Unbind an event callback function
ginput()Get coordinate points via mouse clicks
waitforbuttonpress()Wait for a mouse or keyboard press and return the event type
findobj()Find Artist objects matching the specified condition
get()Get the property value of an Artist object
getp()Get the properties of an Artist object (alias for 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 logging level
xkcd()Switch to xkcd (hand-drawn comic) style

Axes Object - Complete Method List

Axes (Axes object) represents a subplot within a Figure, containing data, ticks, labels, titles, etc. Below is a complete list of all methods organized by official categories.

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()Filled polygon
Axes.fill_between()Horizontal filled region
Axes.fill_betweenx()Vertical filled region
Axes.stackplot()Stacked area chart
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 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 box plot from precomputed statistics
Axes.violinplot()Violin plot
Axes.violin()Draw 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()Hexagonal bin plot
Axes.stairs()Step 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()Quick pseudocolor (drawn using 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 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 (quiver 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 limits
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 level
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 cycle of properties such as line color/line style

14. Axis and Tick Control

Axis access:

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

Axis limits 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()Reverse the x-axis direction
Axes.invert_yaxis()Reverse the y-axis direction
Axes.xaxis_inverted() / yaxis_inverted()Query whether the axis is reversed
Axes.set_xinverted() / get_xinverted()Set/get whether the x-axis is reversed
Axes.set_yinverted() / get_yinverted()Set/get whether the y-axis is reversed
Axes.update_datalim()Expand 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 handles and labels of the legend

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 the data margins
Axes.relim()Recompute the data limits based on the current Artist
Axes.use_sticky_edges()Use sticky margins
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 autoscaling is enabled
Axes.set_autoscalex_on() / get_autoscalex_on()Set/get whether the x-axis is autoscaled
Axes.set_autoscaley_on() / get_autoscaley_on()Set/get whether the y-axis is autoscaled

Aspect ratio:

MethodDescription
Axes.set_aspect() / get_aspect()Set/get the axes aspect ratio ('equal'/'auto'/numeric value)
Axes.set_box_aspect() / get_box_aspect()Set/get the Axes box aspect ratio
Axes.apply_aspect()Apply the current aspect ratio settings
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 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 a unit converter
Axes.convert_yunits()Convert y values using a unit converter
Axes.have_units()Check whether a unit converter is registered

16. Adding Artists

MethodDescription
Axes.add_artist()Add any Artist object
Axes.add_child_axes()Add 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 another Axes
Axes.sharey()Share the y-axis with another 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 to be redrawn (property)
Axes.pchanged()Mark 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 panning/zooming 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 in the toolbar
Axes.format_cursor_data()Format the data value at the cursor position
Axes.format_xdata() / format_ydata()Format the 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 the 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 Artist Query

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 conditions

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 bounds of the Axes 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 rasterization zorder threshold

23. Projection (to be overridden by subclasses)

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()x-axis bottom label transform
Axes.get_xaxis_text2_transform()x-axis top label transform
Axes.get_yaxis_text1_transform()y-axis left label transform
Axes.get_yaxis_text2_transform()y-axis right label transform

24. Other Methods

MethodDescription
Axes.set()Set properties in batch
Axes.zorderGet/set zorder (property)
Axes.get_figure()Get the owning Figure object
Axes.figureOwning 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 the Artists to be additionally included in the bounding box calculation
Axes.get_transformed_clip_path_and_affine()Get the transformed clipping path
Axes.viewLimView range (property)
Axes.dataLimData range (property)
Axes.spinesBorder line dictionary (property)

Figure Object - Complete Method List

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

1. Adding Axes and SubFigures

MethodDescription
Figure.subplots()RecommendedCreate a grid of Axes subplots
Figure.add_subplot()Add a single subplot by row and column position
Figure.add_axes()Add Axes at a specified position and size
Figure.subplot_mosaic()Create complex subplot arrangements using label layout
Figure.add_gridspec()Add a GridSpec layout object
Figure.subfigures()Create a nested sub Figure
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 the axis labels of all subplots
Figure.align_xlabels()Align the x-axis labels of all subplots
Figure.align_ylabels()Align the y-axis labels of all subplots
Figure.align_titles()Align the 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 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 (no longer recommended)
Figure.set_tight_layout() / get_tight_layout()Set/get tight_layout (no longer recommended)
Figure.set_constrained_layout() / get_constrained_layout()Set/get constrained_layout (no longer recommended)
Figure.set_constrained_layout_pads() / get_constrained_layout_pads()Set/get constrained_layout margins (no longer recommended)

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 border line width
Figure.set_facecolor() / get_facecolor()Set/get the Figure background color
Figure.set_edgecolor() / get_edgecolor()Set/get the Figure border color

8. Adding and Getting Artists

MethodDescription
Figure.add_artist()Add any 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()Calculate the 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 bounds of Figure in the display window

10. Helper Functions

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

SubFigure Object - Method List

SubFigure is a logical child figure nested in the parent Figure, with methods similar to Figure.

Adding Axes

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

Annotations

MethodsDescription
SubFigure.suptitle() / get_suptitle()SubFigure overall title
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

MethodsDescription
SubFigure.add_artist()Add Artist
SubFigure.get_children()Get child Artist
SubFigure.set_frameon() / get_frameon()Set/Get border
SubFigure.set_linewidth() / get_linewidth()Set/Get line width
SubFigure.set_facecolor() / get_facecolor()Set/Get background color
SubFigure.set_edgecolor() / get_edgecolor()Set/Get border color
SubFigure.set_dpi() / get_dpi()Set/Get DPI

Style Configuration Quick Reference

Built-in Style Sheets

Viaplt.style.use('name')switch styles.

Style nameStyle description
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 dark palette
seaborn-v0_8-darkgridseaborn dark with grid
seaborn-v0_8-deepseaborn deep tones
seaborn-v0_8-mutedseaborn muted tones
seaborn-v0_8-notebookseaborn notebook style
seaborn-v0_8-paperseaborn paper style
seaborn-v0_8-pastelseaborn pastel tones
seaborn-v0_8-posterseaborn poster style
seaborn-v0_8-talkseaborn talk style
seaborn-v0_8-ticksseaborn ticks style
seaborn-v0_8-whiteseaborn white background
seaborn-v0_8-whitegridseaborn white with grid
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 Configuration

ParameterDescriptionExample value
figure.figsizeDefault figure size (inches)[8, 6]
figure.dpiDefault resolution100
figure.facecolorFigure background color'white'
figure.edgecolorFigure border 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 show the top borderTrue
axes.spines.rightWhether to show the right borderTrue
lines.linewidthDefault line width1.5
lines.markersizeDefault marker size6
lines.linestyleDefault line style'-'
legend.locDefault legend position'best'
legend.fontsizeLegend font size'medium'
xtick.labelsizex-axis tick label size'medium'
ytick.labelsizey-axis tick label size'medium'
savefig.dpiDefault DPI for saving images'figure'
savefig.bboxBounding box mode when savingNone
image.cmapDefault colormap'viridis'
image.interpolationImage interpolation method'antialiased'

Colormap Quick Reference

CategoryColormap nameApplicable scenario
Perceptually uniform (Sequential)viridis, plasma, inferno, magma, cividisContinuous data, colorblind-friendly, recommended first choice
Sequential (single-hue 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., angle, 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 has been the default colormap since Matplotlib 2.0, with excellent perceptual uniformity and colorblind-friendliness, making it the first choice in most scenarios. Avoid using'jet'and'rainbow', as they have perceptual distortion issues.


Common Examples

Example 1: Basic Line Plot and Scatter Plot

Create a chart containing multiple curves and annotations using the explicit Axes interface.

Example

import matplotlib.pyplot as plt
import numpy as np

# Generate data: 100 equally spaced points from 0 to 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)

# Decoration: 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: Multi-subplot Layout (2x2)

Demonstrates 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 2x2 subplots (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 chart
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

Demonstrates visualizing 2D data in the same Figure using both 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 contours (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 the appearance and save high-quality images.

Example

import matplotlib.pyplot as plt
import numpy as np

# Use 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 high-quality PNG at 300 DPI
fig.savefig('example_damped_oscillation.png',
            dpi=300, bbox_inches='tight')
print("example: figure saved successfully")

plt.show()

Example 5: Complex Layout with Mosaic

Use subplot_mosaic to create non-uniform subplot arrangements.

Example

import matplotlib.pyplot as plt
import numpy as np

# Mosaic string defines the layout:
# 'A' spans the entire top row, 'B' and 'C' are at the bottom-left and middle-left, 'D' vertically occupies the bottom-right
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 chart (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: Dual Y-Axes and Inset Axes

Demonstrates 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-axis (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 in on 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()

Frequently Asked Questions

Charts Not Displaying

Confirm whether you calledplt.show()。

Must be explicitly called under non-interactive backends (e.g., Agg)show()。

In Jupyter Notebook, use%matplotlib inlineThe magic command ensures charts are displayed inline.

Too Many Ticks or Wrong Tick Order

The common cause is passing a list of strings as data (rather than numeric or datetime values).

Matplotlib treats string lists as categorical variables, with one tick per unique value, arranged in order of appearance.

Solution: convert strings to numeric values, e.g.np.asarray(data, dtype='float')ornp.asarray(data, dtype='datetime64[s]')。

Chinese Characters Displayed 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 the corresponding font is installed on the system.

Labels Overlapping or Truncated

Recommended to use when creating a Figurelayout='constrained'orlayout='compressed'parameter, which automatically handles overlapping labels, titles, and legends.

You can also usefig.tight_layout()orfig.subplots_adjust()manual adjustment.

Differences Between pcolor and pcolormesh

pcolor()Creates a PolyCollection, slower but more accurate rendering.

pcolormesh()Creates a QuadMesh, faster rendering, recommended for most scenarios.

For very large grids,pcolorfast()use the imshow method for plotting, fastest but least accurate.


Related Resources

  • Matplotlib official website: matplotlib.org
  • Official 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