Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib Common Functions

Matplotlib adopts the function

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

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


Two Programming Interfaces

Matplotlib provides two ways of use, 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 chart
Applicable scenarios Complex charts, multiple subplots, and cases requiring fine-grained control Quick plotting, interactive exploration, and simple charts
Code Example fig, ax = plt.subplots(); ax.plot(x, y) plt.plot(x, y); plt.title("Title")
Recommendation Recommended (clearer and 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 also lists pyplot functions and their corresponding Axes methods.


pyplot Module - Complete List of Functions

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

1. Figure and Axes Management

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

function Description
figure() Create a new Figure or activate an existing Figure
subplots() Recommended: Create 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 a complex non-uniform layout using a label string
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 a specified Axes from a Figure
fignum_exists() Check whether a Figure with the specified number exists
get_figlabels() Return a list of labels of all Figures
get_fignums() Return a list of numbers of all Figures
twinx() Create a secondary y-axis sharing the x-axis
twiny() Create a secondary x-axis sharing the y-axis

2. Basic Plotting

The most commonly used chart type plotting functions.

function Description
plot() Plot a line chart (most commonly used)
scatter() Plot a scatter chart, supporting size/color/alpha mapping
bar() Plot a vertical bar chart
barh() Plot a horizontal bar chart
bar_label() Add value labels on the bars of a bar chart
grouped_bar() Plot a grouped bar chart
pie() Draw the pie chart
pie_label() Add labels to a pie chart
stem() Plot a stem chart (lollipop chart)
eventplot() Plot an event chart (multiple horizontal lines marking event positions)
step() Plot a step chart
fill() Plot a filled polygon
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 a horizontal broken bar chart (Gantt chart style)
vlines() Plot a vertical reference line
hlines() Plot a horizontal reference line
errorbar() Plot a line chart with error bars
loglog() Log-log scale line chart
semilogx() Line chart with logarithmic x-axis
semilogy() Line chart with logarithmic y-axis
polar() Plot in polar coordinates

3. Spans

Plot horizontal and vertical reference lines and shaded regions.

function Description
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 infinitely long straight line passing through two points

4. Spectrum Analysis

Functions for signal processing and spectrum visualization.

function Description
acorr() Plot an autocorrelation chart
xcorr() Plot a cross-correlation chart
angle_spectrum() Plot an angle spectrum
magnitude_spectrum() Plot an amplitude spectrum
phase_spectrum() Plot a phase spectrum
psd() Plot a power spectral density
csd() Plot a cross spectral density
cohere() Plot coherence
specgram() Plot a spectrogram (time-frequency chart)

5. Statistical Charts

Plot charts related to statistical distributions.

function Description
boxplot() Draw box plot
violinplot() Plot a violin chart
ecdf() Plot an empirical cumulative distribution function (ECDF)

6. Binning and Histograms

function Description
hist() Plot a one-dimensional histogram
hist2d() Plot a two-dimensional histogram
hexbin() Plot a hexagonal binning chart
stairs() Plot a step histogram (new version, replacing the step mode of hist)

7. Contours

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

8. 2D Arrays and Images

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

function Description
imshow() Display an image or a 2D array (heatmap)
matshow() Display a matrix as an image in a new Figure
pcolor() Plot a pseudocolor mesh chart (creating a PolyCollection)
pcolormesh() Plot a pseudocolor mesh chart (creating a QuadMesh, with 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 Meshes

function Description
triplot() Plot an unstructured triangular mesh
tripcolor() Plot a pseudocolor chart of a triangular mesh
tricontour() Plot contours on a triangular mesh
tricontourf() Plot filled contours on a triangular mesh

10. Text and Annotations

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

11. Vector Fields

function Description
quiver() Plot a vector field (quiver chart)
quiverkey() Add a legend key to a vector field
barbs() Plot a barbs chart (representing wind speed and direction in meteorology)
streamplot() Plot a streamplot

12. Axis Configuration

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

function Description
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 the parameters of the tick locator
minorticks_on() Show minor ticks
minorticks_off() Hide minor ticks
rgrids() Get or set the radial grid lines of a polar plot
thetagrids() Get or set the angular grid lines of a polar plot
grid() Turn grid lines on or off
axis() Convenience functions to get or set certain axis properties
box() Turn the Axes spines on or off
autoscale() Automatically scale the axes to fit the data

13. Layout

Functions for controlling subplot arrangement and spacing.

function Description
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 the data margins of the axes
subplot_tool() Launch the interactive subplot adjustment tool window

14. Colormaps

Functions related to colormaps and color bars.

function Description
colorbar() Add a color bar
clim() Set the data range of the colormap
get_cmap() Get the colormap object with the specified name
set_cmap() Set the default colormap
gci() Get the current image object with mappable colors
sci() Set the current image object with mappable colors
imread() Read an image from a file into an array
imsave() Save an array as an image file
colormaps colormap registry object
color_sequences color sequence registry object

15. Configuration

Functions for managing Matplotlib's global configuration parameters.

function Description
rc() Set rc parameters (can be set in batches)
rc_context() Context manager for temporarily setting rc parameters
rcdefaults() Restore all rc parameters to their default values

16. Output and Interaction

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

function Description
show() Show 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 the pause)
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() Switching backends

17. Other Utility Functions

function Description
connect() Bind an event callback function
disconnect() Unbind an event callback function
ginput() Get a coordinate point via a mouse click
waitforbuttonpress() Wait for a mouse or key press, returning the event type
findobj() Find Artist objects matching a specified condition
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 the xkcd (hand-drawn cartoon) style

Axes Object - Complete List of Methods

Axes (the Axes object) represents a subplot in a Figure, containing data, ticks, labels, title, etc. The following completely lists all methods by official category.

1. Basic Plotting Methods

Method Description
Axes.plot() Line chart
Axes.scatter() Scatter chart
Axes.bar() Vertical bar chart
Axes.barh() Horizontal bar chart
Axes.bar_label() Add value labels on the bars
Axes.grouped_bar() Grouped bar chart
Axes.pie() Pie chart
Axes.pie_label() Pie chart labels
Axes.stem() Stem chart
Axes.eventplot() Event chart
Axes.step() Step chart
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 chart with error bars
Axes.loglog() Log-log scale
Axes.semilogx() Logarithmic x-axis
Axes.semilogy() Logarithmic y-axis

2. Span Line Methods

Method Description
Axes.axhline() Horizontal reference line
Axes.axvline() Vertical reference line
Axes.axhspan() Horizontal shaded band
Axes.axvspan() Vertical shaded band
Axes.axline() Infinitely long straight line passing through two points

3. Spectrum Analysis Methods

Method Description
Axes.acorr() Autocorrelation chart
Axes.xcorr() Cross-correlation chart
Axes.angle_spectrum() Angle spectrum
Axes.magnitude_spectrum() Amplitude spectrum
Axes.phase_spectrum() Phase spectrum
Axes.psd() Power spectral density
Axes.csd() Cross spectral density
Axes.cohere() Coherence
Axes.specgram() Spectrogram (time-frequency chart)

4. Statistical Methods

Method Description
Axes.boxplot() Boxplot
Axes.bxp() Plot a box chart from precomputed statistics
Axes.violinplot() Violin Plot
Axes.violin() Plot a violin chart from precomputed statistics
Axes.ecdf() Empirical Cumulative Distribution Function

5. Binning and Histogram Methods

Method Description
Axes.hist() Histogram
Axes.hist2d() 2D Histogram
Axes.hexbin() Hexagonal Binning Plot
Axes.stairs() Step Histogram

6. Contour Methods

Method Description
Axes.contour() Contour Lines
Axes.contourf() Filled Contours
Axes.clabel() Contour Labels

7. 2D Array Methods

Method Description
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 Mesh Methods

Method Description
Axes.triplot() Triangular Mesh Lines
Axes.tripcolor() Triangular Mesh Pseudocolor
Axes.tricontour() Triangular Mesh Contours
Axes.tricontourf() Triangular Mesh Filled Contours

9. Text and Annotation Methods

Method Description
Axes.text() Add text
Axes.annotate() Add an annotation with an arrow
Axes.table() Add Table
Axes.arrow() Add an arrow
Axes.inset_axes() Create Inset Axes within Axes
Axes.indicate_inset() Mark Inset Axes Region on Parent Axes
Axes.indicate_inset_zoom() Mark the Magnified Region of Inset Axes
Axes.secondary_xaxis() Add Secondary x-axis (show the same data at another position)
Axes.secondary_yaxis() Add Secondary y-axis

10. Vector Field Methods

Method Description
Axes.quiver() Vector Field (Quiver Plot)
Axes.quiverkey() Vector Field Legend Scale
Axes.barbs() Barbs Plot
Axes.streamplot() Streamplot

11. Clearing Methods

Method Description
Axes.cla() Clear All Contents in Axes
Axes.clear() Clear Axes (same as cla())

12. Appearance Methods

Method Description
Axes.axis() Set Axis Visibility or Range
Axes.set_axis_off() Hide Axes
Axes.set_axis_on() Show Axes
Axes.set_frame_on() Show Axes Frame
Axes.get_frame_on() Get Whether Frame Is Visible
Axes.set_axisbelow() Set Whether Grid/Ticks Are Below Data
Axes.get_axisbelow() Get Grid/Tick Layer
Axes.grid() Set Grid Lines
Axes.get_facecolor() Get Axes Background Color
Axes.set_facecolor() Set Axes Background Color

13. Property Cycling

Method Description
Axes.set_prop_cycle() Set the Cycling of Properties Such as Line Color/Line Style

14. Axis and Tick Control

Axis Access:

Method Description
Axes.xaxis / Axes.yaxis Get the Axis Object of the x/y Axis (property)
Axes.get_xaxis() / get_yaxis() Get the Axis Object of the x/y Axis

Axis Range and Direction:

Method Description
Axes.set_xlim() / get_xlim() Set/Get x-axis Range
Axes.set_ylim() / get_ylim() Set/Get y-axis Range
Axes.set_xbound() / get_xbound() Set/Get Lower and Upper Bounds of x-axis
Axes.set_ybound() / get_ybound() Set/Get Lower and Upper Bounds of y-axis
Axes.invert_xaxis() Invert x-axis Direction
Axes.invert_yaxis() Invert y-axis Direction
Axes.xaxis_inverted() / yaxis_inverted() Query Whether an Axis Is Inverted
Axes.set_xinverted() / get_xinverted() Set/Get Whether x-axis Is Inverted
Axes.set_yinverted() / get_yinverted() Set/Get Whether y-axis Is Inverted
Axes.update_datalim() Extend the Data Range with New Data Points

Axis Labels and Legends:

Method Description
Axes.set_xlabel() / get_xlabel() Set/Get x-axis Label
Axes.set_ylabel() / get_ylabel() Set/Get y-axis Label
Axes.label_outer() Keep Tick Labels Only on Outermost Subplots
Axes.set_title() / get_title() Set/Get 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:

Method Description
Axes.set_xscale() / get_xscale() Set/Get x-axis Scale
Axes.set_yscale() / get_yscale() Set/Get y-axis Scale

Autoscaling and Margins:

Method Description
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() Recompute the Data Range from Current Artists
Axes.use_sticky_edges() Use Sticky Margins
Axes.set_xmargin() / get_xmargin() Set/Get x-axis Margins
Axes.set_ymargin() / get_ymargin() Set/Get y-axis Margins
Axes.set_autoscale_on() / get_autoscale_on() Set/Get Whether to Autoscale
Axes.set_autoscalex_on() / get_autoscalex_on() Set/Get Whether x-axis Autoscales
Axes.set_autoscaley_on() / get_autoscaley_on() Set/Get Whether y-axis Autoscales

Aspect Ratio:

Method Description
Axes.set_aspect() / get_aspect() Set/Get the Axis Aspect Ratio ('equal'/'auto'/numeric)
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:

Method Description
Axes.set_xticks() / get_xticks() Set/Get x-axis Tick Positions
Axes.set_yticks() / get_yticks() Set/Get y-axis Tick Positions
Axes.set_xticklabels() / get_xticklabels() Set/Get x-axis Tick Labels
Axes.set_yticklabels() / get_yticklabels() Set/Get y-axis Tick Labels
Axes.get_xmajorticklabels() Get x-axis Major Tick Labels
Axes.get_xminorticklabels() Get x-axis Minor Tick Labels
Axes.get_ymajorticklabels() Get y-axis Major Tick Labels
Axes.get_yminorticklabels() Get y-axis Minor Tick Labels
Axes.get_xgridlines() Get x-axis Grid Lines
Axes.get_ygridlines() Get y-axis Grid Lines
Axes.get_xticklines() Get x-axis Tick Lines
Axes.get_yticklines() Get y-axis Tick Lines
Axes.xaxis_date() Set x-axis Ticks to Date Format
Axes.yaxis_date() Set 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

Method Description
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

Method Description
Axes.add_artist() Add an Arbitrary 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 and Shared Axes

Method Description
Axes.twinx() Create a secondary y-axis sharing the x-axis
Axes.twiny() Create a secondary 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 the Shared x-axis
Axes.get_shared_y_axes() Get the Grouper Object for the Shared y-axis

18. Axes Position

Method Description
Axes.get_position() / set_position() Get/Set the Position and Size of Axes in the Figure
Axes.get_anchor() / set_anchor() Get/Set the Anchor of Axes (fixed position)
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 Axes Position to Original Value

19. Asynchronous / Events

Method Description
Axes.stale Mark Whether an Artist Needs Redrawing (property)
Axes.pchanged() Mark Property Change Events
Axes.add_callback() Add a Property Change Callback
Axes.remove_callback() Remove a Property Change Callback

20. Interaction

Method Description
Axes.can_pan() / can_zoom() Return Whether Panning/Zooming Is Possible
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 a Pan Operation
Axes.format_coord() Format the Coordinate String Displayed in 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 Query

Method Description
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 a Condition

22. Drawing

Method Description
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 zorder Threshold for Rasterization

23. Projections (to Be Overridden by Subclasses)

Method Description
Axes.name Projection Name (e.g. 'rectilinear', 'polar')
Axes.get_xaxis_transform() / get_yaxis_transform() Get the x/y Axis Transforms
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

Method Description
Axes.set() Set Multiple Properties at Once
Axes.zorder Get/Set zorder (property)
Axes.get_figure() Get the Parent Figure Object
Axes.figure Parent 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 Include Extra in Bounding Box Calculation
Axes.get_transformed_clip_path_and_affine() Get the Transformed Clip Path
Axes.viewLim View Range (property)
Axes.dataLim Data Range (property)
Axes.spines Frame Line Dictionary (property)

Figure Object - Complete List of Methods

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

1. Adding Axes and SubFigure

Method Description
Figure.subplots() Recommended: Create 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 SubFigure
Figure.add_subfigure() Add a Single SubFigure
Figure.axes Axes List (property)
Figure.get_axes() Get All Axes
Figure.delaxes() Remove the Specified Axes

2. Saving

Method Description
Figure.savefig() Save the Figure to a File

3. Figure-Level Annotation

Method Description
Figure.suptitle() / get_suptitle() Set/Get the Overall Figure Title
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 color bar
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

Method Description
Figure.set_size_inches() / get_size_inches() Set/Get the Figure Size (inches)
Figure.set_figheight() / get_figheight() Set/Get the Figure Height
Figure.set_figwidth() / get_figwidth() Set/Get the Figure Width
Figure.dpi DPI Resolution (property)
Figure.set_dpi() / get_dpi() Set/Get DPI

5. Subplot Layout

Method Description
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

Method Description
Figure.ginput() Get a coordinate point via a mouse click
Figure.waitforbuttonpress() Wait for a Mouse or Key Press
Figure.pick() Trigger a pick Event
Figure.add_axobserver() Add an Axes Observer

7. Appearance Modification

Method Description
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

Method Description
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

Method Description
Figure.clear() Clear the Figure
Figure.gca() Get the Current Axes
Figure.sca() Set the current Axes
Figure.show() Display the Figure
Figure.draw() Render the Figure
Figure.draw_artist() Draw a Single Artist
Figure.draw_without_rendering() Compute 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 the Figure in the Display Window

10. Helper Functions

function Description
figaspect() Compute the Figure Size from a Specified Aspect Ratio

SubFigure Object - Method List

SubFigure is a logical sub-Figure nested within a parent Figure, with methods similar to those of Figure.

Add Axes

Method Description
SubFigure.subplots() Create a 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 More Deeply Nested SubFigure
SubFigure.add_subfigure() Add a Single SubFigure
SubFigure.delaxes() Remove Axes

Annotations

Method Description
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

Artists and Appearance

Method Description
SubFigure.add_artist() Add 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 DPI

Style Configuration Quick Reference

Built-in Style Sheets

Pass plt.style.use('name') Switch Styles.

Style Name Style Description
default Default style, clean and neutral
ggplot Imitates the R ggplot2 style, gray background with white grid
seaborn-v0_8 Modern style similar to the seaborn library
seaborn-v0_8-bright seaborn bright tones
seaborn-v0_8-colorblind seaborn colorblind-friendly tones
seaborn-v0_8-dark seaborn dark style
seaborn-v0_8-dark-palette seaborn dark color palette
seaborn-v0_8-darkgrid seaborn dark with grid
seaborn-v0_8-deep seaborn dark tones
seaborn-v0_8-muted seaborn muted tones
seaborn-v0_8-notebook seaborn notebook style
seaborn-v0_8-paper seaborn paper style
seaborn-v0_8-pastel seaborn pastel tones
seaborn-v0_8-poster seaborn poster style
seaborn-v0_8-talk seaborn talk style
seaborn-v0_8-ticks seaborn ticks style
seaborn-v0_8-white seaborn white background
seaborn-v0_8-whitegrid seaborn white with grid
fivethirtyeight Imitates the FiveThirtyEight data journalism style
dark_background Dark background, suitable for presentations and night use
bmh Bayesian Methods for Hackers style
grayscale Grayscale style, suitable for black-and-white printing
classic Matplotlib v1.x classic style
fast Simplified style, faster rendering
Solarize_Light2 Solarized light theme
tableau-colorblind10 Tableau colorblind-friendly color palette

Common rcParams Configurations

Parameters Description Example value
figure.figsize Default Figure Size (inches) [8, 6]
figure.dpi Default Resolution 100
figure.facecolor Figure Background Color 'white'
figure.edgecolor Figure Frame Color 'white'
font.size Global Font Size 12
font.family Font Family 'sans-serif'
font.sans-serif Sans-serif Font List ['DejaVu Sans', ...]
axes.titlesize Title Font Size 'large'
axes.labelsize Axis Label Font Size 'medium'
axes.grid Whether to Show Grid by Default False
axes.facecolor Axes Background Color 'white'
axes.spines.top Whether to Show the Top Frame True
axes.spines.right Whether to Show the Right Frame True
lines.linewidth Default Line Width 1.5
lines.markersize Default Marker Size 6
lines.linestyle Default Line Style '-'
legend.loc Default Legend Location 'best'
legend.fontsize Legend Font Size 'medium'
xtick.labelsize x-axis Tick Label Size 'medium'
ytick.labelsize y-axis Tick Label Size 'medium'
savefig.dpi Default Resolution for Saved Images 'figure'
savefig.bbox Bounding Mode When Saving None
image.cmap Default colormap 'viridis'
image.interpolation Image Interpolation Method 'antialiased'

colormap (Color Map) Quick Reference

Classification colormap Name Applicable scenarios
Perceptually Uniform (Sequential) viridis, plasma, inferno, magma, cividis Continuous data, colorblind-friendly, recommended first choice
Sequential (Monochrome Gradient) Greys, Purples, Blues, Greens, Oranges, Reds, YlOrBr, YlOrRd, OrRd, PuRd, RdPu, BuPu, GnBu, PuBu, YlGnBu, PuBuGn, BuGn, YlGn Continuous data from low to high, single hue
Diverging PiYG, PRGn, BrBG, PuOr, RdGy, RdBu, RdYlBu, RdYlGn, Spectral, coolwarm, bwr, seismic Bidirectional data with a central reference point
Cyclic twilight, twilight_shifted, hsv Periodic data (e.g. angles, time)
Qualitative Pastel1, Pastel2, Paired, Accent, Dark2, Set1, Set2, Set3, tab10, tab20, tab20b, tab20c Discrete categorical data
Miscellaneous flag, prism, ocean, gist_earth, terrain, gist_stern, gnuplot, gnuplot2, CMRmap, cubehelix, brg, gist_rainbow, rainbow, jet, turbo, nipy_spectral, gist_ncar Special purposes or visual effects

'viridis' Has been the default colormap since Matplotlib 2.0, with excellent perceptual uniformity and colorblind-friendly properties, making it the first choice for most scenarios. Avoid using 'jet' and 'rainbow', as they suffer from perceptual distortion.


Common examples

Example 1: Basic Line and Scatter Plots

Use the explicit Axes interface to create a chart 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'

)

Draw two lines, setting color, line style, 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

)

Decorations: 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

(

"runoob: 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

pi

,

100

)

Create a 2x2 subplot (object-oriented interface)

fig

,

axes

=

plt.

subplots

(

2

,

2

,

figsize

=

(

10

,

8

)

,

layout

=

'constrained'

)

fig.

suptitle

(

'Multi-panel RUNOOB 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 Comparison

Demonstrate two ways to visualize 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

)

cos

(

Y

)

 

2D function values

fig

,

(

ax1

,

ax2

)

=

plt.

subplots

(

1

,

2

,

figsize

=

(

12

,

5

)

,

                                layout

=

'constrained'

)

Left plot: 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 plot: 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 Images

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

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

)

sin

(

2

)

 

Damped sine wave

y2

=

np.

exp

(

-x/

3

)

cos

(

2

)

 

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

(

'runoob_damped_oscillation.png'

,

            dpi

=

300

,

bbox_inches

=

'tight'

)

print

(

"runoob: figure saved successfully"

)

plt.

show

(

)

Example 5: Complex mosaic Layout

Use subplot_mosaic to create a non-uniform subplot arrangement.

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

The mosaic string defines the layout:

'A' spans the entire top row, 'B' and 'C' are at bottom-left and middle-left, 'D' occupies 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 (RUNOOB)'

,

fontsize

=

16

)

Panel A: Line plot (spanning 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-axis and Inset Axes

Demonstrate the use 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 a dual y-axis (sharing the 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 inset axes in ax (magnify 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 questions

Chart does not display

Check whether you called plt.show()。

Must be called explicitly under a non-interactive backend (such as Agg) show()。

In Jupyter Notebook, use %matplotlib inline magic command to ensure the chart is displayed inline.

Too many ticks or out-of-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, one tick per unique value, arranged in order of appearance.

Solution: Convert strings to numbers, such as np.asarray(data, dtype='float') or np.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.

Settings plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', ...] And make sure the corresponding font is installed on the system.

Labels overlap or are truncated

Recommended to use when creating the Figure layout='constrained' or layout='compressed' parameter to automatically handle overlap of labels, titles, and legends.

You can also use fig.tight_layout() or fig.subplots_adjust() Adjust manually.

Difference Between pcolor and pcolormesh

pcolor() Creates a PolyCollection, which renders more slowly but is more accurate.

pcolormesh() Creates a QuadMesh, which renders faster and is the recommended choice for most scenarios.

For very large grids,pcolorfast() use the imshow approach, which is the fastest but least accurate.


Related Resources