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.
| Function | Related Content |
|---|---|
| Matplotlib plot() Function | plot() |
| Matplotlib scatter() Function | scatter() |
| Matplotlib bar() / barh() Function | bar(), barh(), bar_label(), grouped_bar() |
| Matplotlib hist() Function | hist() |
| Matplotlib pie() Function | pie(), pie_label() |
| Matplotlib imshow() Function | imshow() |
| Matplotlib subplots() Function | subplots() |
| Matplotlib figure() Function | figure() |
| Matplotlib savefig() Function | savefig() |
| Matplotlib errorbar() Function | errorbar() |
| Matplotlib boxplot() Function | boxplot() |
| Matplotlib contour() / contourf() Function | contour(), contourf(), clabel() |
| Matplotlib fill_between() / fill_betweenx() Function | fill_between(), fill_betweenx() |
| Matplotlib legend() Function | legend() |
| Matplotlib text() / annotate() Function | text(), annotate() |
| Matplotlib Title and Label Functions | title(), xlabel(), ylabel(), suptitle(), supxlabel(), supylabel() |
| Matplotlib colorbar() Function | colorbar() |
| Matplotlib Figure and Axes Management Functions | axes(), cla(), clf(), close(), delaxes(), fignum_exists(), gca(), gcf(), get_figlabels(), get_fignums(), sca(), subplot(), subplot2grid(), subplot_mosaic(), twinx(), twiny() |
| Matplotlib Advanced Plotting Functions | step(), stem(), eventplot(), stackplot(), broken_barh(), vlines(), hlines(), fill(), loglog(), semilogx(), semilogy() |
| Matplotlib Span and Vector Field Functions | axhline(), axhspan(), axvline(), axvspan(), axline(), quiver(), quiverkey(), barbs(), streamplot() |
| Matplotlib Spectral Analysis Functions | acorr(), xcorr(), psd(), csd(), specgram(), cohere(), angle_spectrum(), magnitude_spectrum(), phase_spectrum() |
| Matplotlib 2D Data and Statistical Plot Functions | hist2d(), hexbin(), stairs(), matshow(), pcolor(), pcolormesh(), spy(), figimage(), ecdf(), violinplot() |
| Matplotlib Triangulation and Polar Coordinate Functions | triplot(), tripcolor(), tricontour(), tricontourf(), polar(), rgrids(), thetagrids() |
| Matplotlib Axis Configuration Functions | xlim(), ylim(), xscale(), yscale(), xticks(), yticks(), tick_params(), ticklabel_format(), locator_params(), minorticks_on(), minorticks_off(), grid(), axis(), box(), autoscale() |
| Matplotlib Layout and Configuration Functions | subplots_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 Functions | connect(), disconnect(), ginput(), waitforbuttonpress(), findobj(), get(), setp(), getp(), get_current_fig_manager(), new_figure_manager(), set_loglevel(), xkcd() |
| Matplotlib Figure-level Text and Annotation Functions | figtext(), 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).
| Function | Description |
|---|---|
| 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.
| Function | Description |
|---|---|
| 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.
| Function | Description |
|---|---|
| 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.
| Function | Description |
|---|---|
| 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.
| Function | Description |
|---|---|
| boxplot() | Draw box plot |
| violinplot() | Draw violin plot |
| ecdf() | Draw empirical cumulative distribution function (ECDF) |
6. Binning and Histograms
| Function | Description |
|---|---|
| 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
| Function | Description |
|---|---|
| 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.
| Function | Description |
|---|---|
| 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
| Function | Description |
|---|---|
| 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
| Function | Description |
|---|---|
| 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
| Function | Description |
|---|---|
| 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.
| 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 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.
| Function | Description |
|---|---|
| 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.
| Function | Description |
|---|---|
| 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 |
| colormaps | Colormap registry object |
| color_sequences | Color sequence registry object |
15. Configuration
Functions for managing Matplotlib global configuration parameters.
| Function | Description |
|---|---|
| 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.
| Function | Description |
|---|---|
| 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
| Function | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| Axes.hist() | Histogram |
| Axes.hist2d() | 2D histogram |
| Axes.hexbin() | Hexagonal bin plot |
| Axes.stairs() | Step histogram |
6. Contour Methods
| Method | Description |
|---|---|
| Axes.contour() | Contour |
| Axes.contourf() | Filled contour |
| 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() | Quick pseudocolor (drawn using imshow) |
| Axes.pcolormesh() | Pseudocolor mesh (QuadMesh, recommended) |
| Axes.spy() | Sparse matrix pattern |
8. Unstructured Triangular Grid Methods
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| Axes.cla() | Clear all content in the Axes |
| Axes.clear() | Clear the Axes (same as cla()) |
12. Appearance Methods
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| Axes.set_prop_cycle() | Set the cycle 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 limits and direction:
| Method | Description |
|---|---|
| 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:
| Method | Description |
|---|---|
| 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:
| Method | Description |
|---|---|
| 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:
| 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 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:
| Method | Description |
|---|---|
| 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:
| Method | Description |
|---|---|
| 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
| 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 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| Axes.stale | Mark 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
| Method | Description |
|---|---|
| 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
| 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 the conditions |
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 rasterization zorder threshold |
23. Projection (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 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
| Method | Description |
|---|---|
| Axes.set() | Set properties in batch |
| Axes.zorder | Get/set zorder (property) |
| Axes.get_figure() | Get the owning Figure object |
| Axes.figure | Owning 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.viewLim | View range (property) |
| Axes.dataLim | Data range (property) |
| Axes.spines | Border 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
| Method | Description |
|---|---|
| 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.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 Annotations
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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.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 (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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Method | Description |
|---|---|
| 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
| Function | Description |
|---|---|
| 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
| Methods | Description |
|---|---|
| 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
| Methods | 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 |
Artist and Appearance
| Methods | Description |
|---|---|
| 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 name | Style description |
|---|---|
| default | Default style, clean and neutral |
| ggplot | Mimics R ggplot2 style, gray background with white grid |
| seaborn-v0_8 | Modern style similar to the seaborn library |
| seaborn-v0_8-bright | seaborn bright palette |
| seaborn-v0_8-colorblind | seaborn colorblind-friendly palette |
| seaborn-v0_8-dark | seaborn dark style |
| seaborn-v0_8-dark-palette | seaborn dark palette |
| seaborn-v0_8-darkgrid | seaborn dark with grid |
| seaborn-v0_8-deep | seaborn deep 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 | Mimics FiveThirtyEight data journalism style |
| dark_background | Dark background, suitable for presentations and nighttime 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 palette |
Common rcParams Configuration
| Parameter | 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 border 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 grid is shown by default | False |
| axes.facecolor | Axes background color | 'white' |
| axes.spines.top | Whether to show the top border | True |
| axes.spines.right | Whether to show the right border | True |
| lines.linewidth | Default line width | 1.5 |
| lines.markersize | Default marker size | 6 |
| lines.linestyle | Default line style | '-' |
| legend.loc | Default legend position | '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 DPI for saving images | 'figure' |
| savefig.bbox | Bounding box mode when saving | None |
| image.cmap | Default colormap | 'viridis' |
| image.interpolation | Image interpolation method | 'antialiased' |
Colormap Quick Reference
| Category | Colormap name | Applicable scenario |
|---|---|---|
| Perceptually uniform (Sequential) | viridis, plasma, inferno, magma, cividis | Continuous 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, 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., angle, 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 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 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 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 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 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 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 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