Examples
发布时间:2026-11-01 | 浏览:1
For an overview of the plotting methods we provide, see Plot types
This page contains example plots. Click on any image to see the full image and source code.
For longer tutorials, see our tutorials page . You can also find external resources and a FAQ in our user guide .
You can also browse the example gallery by tags .
Lines, bars and markers #
Dashed line style configuration
Marker reference
Multicolored lines
Lines with a ticked patheffect
Grouped bar chart with labels
Bar chart with labels
Stacked bar chart
Bar chart with individual bar colors
Bar chart with gradients
Horizontal bar chart
Discrete distribution as horizontal bar chart
Broken horizontal bars
Mapping marker properties to multivariate data
Marker examples
Scatter plot with a legend
Scatter plot with masked values
Scatter plot with histograms
fill_between with transparency
Fill the area between two lines
Fill the area between two vertical lines
Stackplots and streamgraphs
EventCollection Demo
Timeline with lines, dates, and text
hlines and vlines
Shade regions defined by a logical mask using fill_between
Plotting categorical variables
Plotting masked and NaN values
Spectrum representations
Images, contours and fields #
Many ways to plot images
Image with masked values
Multiple images with one colorbar
Modifying the coordinate formatter
Image resampling
Interpolations for imshow
Layer images with alpha blending
Blend transparency with color in 2D images
Shading example
Clipping images with patches
Placing images, preserving relative sizes
pcolormesh grids and shading
Image nonuniform
Tricontour Demo
Tricontour Smooth User
Tricontour Smooth Delaunay
Trigradient Demo
Contour plot of irregularly spaced data
Contour Label Demo
Contourf and log color scale
Contourf hatching
Contour corner mask
Contouring the solution space of optimizations
Quiver Simple Demo
Advanced quiver and quiverkey functions
Interactive adjustment of colormap range
Colormap normalizations
Colormap normalizations SymLogNorm
Annotated heatmap
Affine transform of an image
Visualize matrices with matshow
Watermark image
Errorbar function
Different ways of specifying error bars
Errorbar subsampling
Errorbar limit selection
Including upper and lower limits in error bars
Create boxes from error bars using PatchCollection
Plot a confidence ellipse of a two-dimensional dataset
Curve with error band
Demo of the histogram function's different histtype settings
Histogram bins, density, and weight
The histogram (hist) function with multiple data sets
Multiple histograms side by side
Cumulative distributions
Hexagonal binned plot
Time Series Histogram
Artist customization in box plots
Box plots with custom fill colors
Separate calculation and plotting of boxplots
Box plot vs. violin plot comparison
Violin plot basics
Violin plot customization
Cross- and auto-correlation
Power spectral density (PSD)
Cross spectral density (CSD)
Plotting the coherence of two signals
Pie and polar charts #
Nested pie charts
A pie and a donut with labels
Labeling pie charts
Bar chart on polar axis
Error bar rendering on polar axis
Scatter plot on polar axis
Subplots, axes and figures #
Multiple subplots
Create multiple subplots using plt.subplots
GridSpec with variable sizes and spacing
Gridspec for multi-column/row subplot layouts
Nested Gridspecs
Combine two subplots using subplots and GridSpec
Resize Axes with constrained layout
Resize Axes with tight layout
Subplots spacings and margins
Programmatically control subplot adjustment
Adjacent subplots
Controlling view limits using margins and sticky_edges
Axes box aspect
Equal axis aspect ratio
Manage multiple figures in pyplot
Figure size in different units
Figure subfigures
Custom Figure subclasses
Plots with different scales
Different scales on the same Axes
Multiple y-axis with Spines
Twin Axes with delta_zorder
Align labels and titles
Axis label position
Axes properties
Figure labels: suptitle, supxlabel, supylabel
Axes zoom effect
Zoom region inset Axes
Geographic Projections
Draw regions that span an Axes
Automatically setting tick positions
Major and minor ticks
Align tick labels
Move x/y-axis ticks and labels on top and right
Center labels between ticks
Rotated tick labels
Multilevel (nested) ticks
The default tick formatter
Tick formatters
Format ticks using engineering notation
SI prefixed offsets and natural order of magnitudes
Setting tick labels from a list of values
Date tick labels
Date tick locators and formatters
Format date ticks using ConciseDateFormatter
Date converter demo
Placing date ticks using recurrence rules
Custom tick formatter for time series
Date precision and epochs
Colorbar Tick labelling
Customizing figure and axes appearance
Fixing too many ticks
These examples cover how different scales are handled in Matplotlib.
Scales overview
Exploring normalizations
Spine placement
Centered spines with arrows
Text, labels and annotations #
Text properties
Controlling style of text and labels using a dictionary
Text rotation mode
Text rotation angle in data coordinates
Concatenate text objects with different properties
Using a text as a Path
Annotating a plot
Annotate polar plots
Angle annotations on bracket arrows
Annotation arrow style reference
Styling text boxes
Placing text boxes
Labelling subplots
Artists as annotations
Scale invariant angle label
Legend using pre-defined labels
Compose custom legends
Figure legend demo
The difference between \dfrac and \frac
Configure the font family
Using ttf font files
Fonts demo (object-oriented style)
Fonts demo (keyword arguments)
Convert texts to images
Mathematical expressions
Math fontfamily
Render math equations using TeX
Usetex text baseline
Usetex font effects
Artist within an artist
Title positioning
Shapes and collections #
Reference for Matplotlib artists
Line, Poly and RegularPoly Collection
Ellipse with orientation arrow demo
Ellipse Collection
Drawing fancy boxes
Hatch style reference
Hatchcolor Demo
Plot multiple lines using a LineCollection
Circles, Wedges and Polygons
PathPatch object
For a description of the colormaps available in Matplotlib, see the colormaps tutorial .
Color by y-value
Colors in the default property cycle
Named color sequences
Histogram as colorbar
Colormap reference
Create a colormap from a list of colors
Selecting individual colors from a colormap
List of named colors
Ways to set a color's alpha value
Bayesian Methods for Hackers style sheet
Dark background style sheet
FiveThirtyEight style sheet
ggplot style sheet
Grayscale style sheet
Petroff style sheets
Solarized Light stylesheet
Style sheets reference
Module - pyplot #
Two subplots using pyplot
Plot 2D data on 3D plot
Demo of 3D bar charts
Clip the data to the axes view limits
Create 2D bar graphs in different planes
3D box surface plot
Plot contour (level) curves in 3D
Plot contour (level) curves in 3D using the extend3d option
Project contour profiles onto a graph
Filled contours
Project filled contour onto a graph
Custom hillshading in a 3D surface plot
Fill between 3D lines
Fill under 3D line graphs
Create 3D histogram of 2D data
2D images in 3D
Intersecting planes
Parametric curve
Lorenz attractor
2D and 3D Axes in same figure
Automatic text offsetting
Draw flat objects in 3D plot
Generate 3D polygons
3D plot projection types
Rotating a 3D plot
Scales on 3D (Log, Symlog, etc.)
3D plots as subplots
3D surface (colormap)
3D surface (solid color)
3D surface (checkerboard)
3D surface with polar coordinates
Text annotations in 3D
Triangular 3D contour plot
Triangular 3D filled contour plot
Triangular 3D surfaces
More triangular 3D surfaces
Primary 3D view planes
3D voxel / volumetric plot
3D voxel plot of the NumPy logo
3D voxel / volumetric plot with RGB colors
3D voxel / volumetric plot with cylindrical coordinates
3D wireframe plot
Animate a 3D wireframe plot
3D wireframe plots in one direction
Module - axes_grid1 #
Anchored Direction Arrow
HBoxDivider and VBoxDivider demo
Show RGB channels using RGBAxes
Colorbar with AxesDivider
Control the position and size of a colorbar with inset_locator.inset_axes
Per-row or per-column colorbars
Axes with a fixed physical size
ImageGrid cells with a fixed aspect ratio
Inset locator demo
Inset locator demo 2
Make room for ylabel using axes_grid
Parasite Simple
Parasite Simple2
Align histogram to scatter plot using locatable Axes
Simple Anchored Artists
Simple Axes Divider 1
Simple axes divider 3
Simple ImageGrid
Simple ImageGrid 2
Simple Axisline4
Module - axisartist #
axis_direction demo
Axis line styles
Curvilinear grid demo
Demo CurveLinear Grid2
floating_axes features
floating_axis demo
Parasite Axes demo
Parasite axis demo
Ticklabel alignment
Ticklabel direction
Simple axis direction
Simple axis tick label and tick directions
Simple axis pad
Custom spines with axisartist
Simple Axisline
Simple Axisline3
Basic animated line plot
Animated histogram
pyplot animation
The Bayes update
The double pendulum problem
Animated image using a precomputed list of images
Multiple Axes animation
Pause and resume an animation
Rain simulation
Animated 3D random walk
Animated scatter saved as GIF
Matplotlib unchained
Examples of how to write primitive, but GUI agnostic, widgets in matplotlib
Annotated cursor
Select indices from a collection using polygon selector
Polygon Selector
Radio Buttons Grid
Image scaling using a RangeSlider
Rectangle and ellipse selectors
Snap sliders to discrete values
Event handling #
Matplotlib supports event handling with a GUI neutral event model, so you can connect to Matplotlib events without knowledge of what user interface Matplotlib will ultimately be plugged in to. This has two advantages: the code you write will be more portable, and Matplotlib events are aware of things like data coordinate space and which axes the event occurs in so you don't have to mess with low level transformation details to go from canvas space to data space. Object picking examples are also included.
Mouse move and click events
Cross-hair cursor
Figure/Axes enter and leave events
Interactive functions
Pick event demo
Pick event demo 2
Resampling Data
Trifinder Event Demo
Zoom modifies other Axes
Embedding Matplotlib in graphical user interfaces #
You can embed Matplotlib directly into a user interface application by following the embedding_in_SOMEGUI.py examples here. Currently Matplotlib supports PyQt/PySide, PyGObject, Tkinter, and wxPython.
When embedding Matplotlib in a GUI, you must use the Matplotlib API directly rather than the pylab/pyplot procedural interface, so take a look at the examples/api directory for some example code working with the API.
Embed in GTK3 with a navigation toolbar
Embed in GTK4 with a navigation toolbar
Embedding WebAgg
Fourier Demo WX
GTK3 spreadsheet
GTK4 spreadsheet
Display mathtext in WX
Matplotlib with Glade 3
mplcvd -- an example of figure hook
pyplot with GTK3
pyplot with GTK4
Embed in a web application server (Flask)
Add a cursor in WX
These examples cover the many representations of units in Matplotlib.
Annotation with units
Bar demo with units
Group barchart with units
Ellipse with units
Inches and centimeters
Miscellaneous #
Anchored Artists
Identify whether artists intersect
Custom projection
Add lines directly to a figure
Font properties
Building histograms using Rectangles and PolyCollections
Plotting with keywords
Matplotlib logo
Multiprocessing
Packed-bubble chart
Patheffect Demo
Print image to stdout
Rasterization for vector graphics
Set and get properties
Apply SVG filter to a line
TickedStroke patheffect
transforms.offset_copy
Anatomy of a figure
Integral as the area under a curve
Shaded & power normalized rendering
Pan/zoom events of overlapping axes
Stock prices over 32 years
Specialty plots #
Anscombe's quartet
Hinton diagrams
Ishikawa Diagram
Left ventricle bullseye
Radar chart (aka spider or star chart)
The Sankey class
Long chain of connections using Sankey
Rankine power cycle
SkewT-logP diagram: using transforms and custom projections
Topographic hillshading
Download all examples in Python source code: gallery_python.zip
Download all examples in Jupyter notebooks: gallery_jupyter.zip
Gallery generated by Sphinx-Gallery