matplotlib.pyplot#

matplotlib.pyplot is a state-based interface to matplotlib. It provides an implicit, MATLAB-like, way of plotting. It also opens figures on your screen, and acts as the figure GUI manager.

pyplot is mainly intended for interactive plots and simple cases of programmatic plot generation:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)

The explicit object-oriented API is recommended for complex plots, though pyplot is still usually used to create the figure and often the axes in the figure. See pyplot.figure, pyplot.subplots, and pyplot.subplot_mosaic to create figures, and Axes API for the plotting methods on an Axes:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)

See Matplotlib Application Interfaces (APIs) for an explanation of the tradeoffs between the implicit and explicit interfaces.

Plotting commands#

acorr

Plot the autocorrelation of x.

angle_spectrum

Plot the angle spectrum.

annotate

Annotate the point xy with text text.

arrow

Add an arrow to the Axes.

autoscale

Autoscale the axis view to the data (toggle).

axes

Add an Axes to the current figure and make it the current Axes.

axhline

Add a horizontal line across the Axes.

axhspan

Add a horizontal span (rectangle) across the Axes.

axis

Convenience method to get or set some axis properties.

axline

Add an infinitely long straight line.

axvline

Add a vertical line across the Axes.

axvspan

Add a vertical span (rectangle) across the Axes.

bar

Make a bar plot.

bar_label

Label a bar plot.

barbs

Plot a 2D field of barbs.

barh

Make a horizontal bar plot.

box

Turn the axes box on or off on the current axes.

boxplot

Draw a box and whisker plot.

broken_barh

Plot a horizontal sequence of rectangles.

cla

Clear the current axes.

clabel

Label a contour plot.

clf

Clear the current figure.

clim

Set the color limits of the current image.

close

Close a figure window.

cohere

Plot the coherence between x and y.

colorbar

Add a colorbar to a plot.

contour

Plot contour lines.

contourf

Plot filled contours.

csd

Plot the cross-spectral density.

delaxes

Remove an Axes (defaulting to the current axes) from its figure.

draw

Redraw the current figure.

draw_if_interactive

Redraw the current figure if in interactive mode.

errorbar

Plot y versus x as lines and/or markers with attached errorbars.

eventplot

Plot identical parallel lines at the given positions.

figimage

Add a non-resampled image to the figure.

figlegend

Place a legend on the figure.

fignum_exists

Return whether the figure with the given id exists.

figtext

Add text to figure.

figure

Create a new figure, or activate an existing figure.

fill

Plot filled polygons.

fill_between

Fill the area between two horizontal curves.

fill_betweenx

Fill the area between two vertical curves.

findobj

Find artist objects.

gca

Get the current Axes.

gcf

Get the current figure.

gci

Get the current colorable artist.

get

Return the value of an Artist's property, or print all of them.

get_cmap

Get a colormap instance, defaulting to rc values if name is None.

get_figlabels

Return a list of existing figure labels.

get_fignums

Return a list of existing figure numbers.

getp

Return the value of an Artist's property, or print all of them.

grid

Configure the grid lines.

hexbin

Make a 2D hexagonal binning plot of points x, y.

hist

Compute and plot a histogram.

hist2d

Make a 2D histogram plot.

hlines

Plot horizontal lines at each y from xmin to xmax.

imread

Read an image from a file into an array.

imsave

Colormap and save an array as an image file.

imshow

Display data as an image, i.e., on a 2D regular raster.

install_repl_displayhook

Connect to the display hook of the current shell.

ioff

Disable interactive mode.

ion

Enable interactive mode.

isinteractive

Return whether plots are updated after every plotting command.

legend

Place a legend on the Axes.

locator_params

Control behavior of major tick locators.

loglog

Make a plot with log scaling on both the x and y axis.

magnitude_spectrum

Plot the magnitude spectrum.

margins

Set or retrieve autoscaling margins.

matshow

Display an array as a matrix in a new figure window.

minorticks_off

Remove minor ticks from the Axes.

minorticks_on

Display minor ticks on the Axes.

pause

Run the GUI event loop for interval seconds.

pcolor

Create a pseudocolor plot with a non-regular rectangular grid.

pcolormesh

Create a pseudocolor plot with a non-regular rectangular grid.

phase_spectrum

Plot the phase spectrum.

pie

Plot a pie chart.

plot

Plot y versus x as lines and/or markers.

plot_date

[Discouraged] Plot coercing the axis to treat floats as dates.

polar

Make a polar plot.

psd

Plot the power spectral density.

quiver

Plot a 2D field of arrows.

quiverkey

Add a key to a quiver plot.

rc

Set the current rcParams. group is the grouping for the rc, e.g., for lines.linewidth the group is lines, for axes.facecolor, the group is axes, and so on. Group may also be a list or tuple of group names, e.g., (xtick, ytick). kwargs is a dictionary attribute name/value pairs, e.g.,::.

rc_context

Return a context manager for temporarily changing rcParams.

rcdefaults

Restore the rcParams from Matplotlib's internal default style.

rgrids

Get or set the radial gridlines on the current polar plot.

savefig

Save the current figure.

sca

Set the current Axes to ax and the current Figure to the parent of ax.

scatter

A scatter plot of y vs.

sci

Set the current image.

semilogx

Make a plot with log scaling on the x axis.

semilogy

Make a plot with log scaling on the y axis.

set_cmap

Set the default colormap, and applies it to the current image if any.

set_loglevel

Set Matplotlib's root logger and root logger handler level, creating the handler if it does not exist yet.

setp

Set one or more properties on an Artist, or list allowed values.

show

Display all open figures.

specgram

Plot a spectrogram.

spy

Plot the sparsity pattern of a 2D array.

stackplot

Draw a stacked area plot.

stairs

A stepwise constant function as a line with bounding edges or a filled plot.

stem

Create a stem plot.

step

Make a step plot.

streamplot

Draw streamlines of a vector flow.

subplot

Add an Axes to the current figure or retrieve an existing Axes.

subplot2grid

Create a subplot at a specific location inside a regular grid.

subplot_mosaic

Build a layout of Axes based on ASCII art or nested lists.

subplot_tool

Launch a subplot tool window for a figure.

subplots

Create a figure and a set of subplots.

subplots_adjust

Adjust the subplot layout parameters.

suptitle

Add a centered suptitle to the figure.

switch_backend

Close all open figures and set the Matplotlib backend.

table

Add a table to an Axes.

text

Add text to the Axes.

thetagrids

Get or set the theta gridlines on the current polar plot.

tick_params

Change the appearance of ticks, tick labels, and gridlines.

ticklabel_format

Configure the ScalarFormatter used by default for linear Axes.

tight_layout

Adjust the padding between and around subplots.

title

Set a title for the Axes.

tricontour

Draw contour lines on an unstructured triangular grid.

tricontourf

Draw contour regions on an unstructured triangular grid.

tripcolor

Create a pseudocolor plot of an unstructured triangular grid.

triplot

Draw an unstructured triangular grid as lines and/or markers.

twinx

Make and return a second axes that shares the x-axis.

twiny

Make and return a second axes that shares the y-axis.

uninstall_repl_displayhook

Disconnect from the display hook of the current shell.

violinplot

Make a violin plot.

vlines

Plot vertical lines at each x from ymin to ymax.

xcorr

Plot the cross correlation between x and y.

xkcd

Turn on xkcd sketch-style drawing mode.

xlabel

Set the label for the x-axis.

xlim

Get or set the x limits of the current axes.

xscale

Set the xaxis' scale.

xticks

Get or set the current tick locations and labels of the x-axis.

ylabel

Set the label for the y-axis.

ylim

Get or set the y-limits of the current axes.

yscale

Set the yaxis' scale.

yticks

Get or set the current tick locations and labels of the y-axis.

Other commands#

connect

Bind function func to event s.

disconnect

Disconnect the callback with id cid.

get_current_fig_manager

Return the figure manager of the current figure.

ginput

Blocking call to interact with a figure.

new_figure_manager

Create a new figure manager instance.

waitforbuttonpress

Blocking call to interact with the figure.

Colormaps#

Colormaps are available via the colormap registry matplotlib.colormaps. For convenience this registry is available in pyplot as

matplotlib.pyplot.colormaps[source]#

Container for colormaps that are known to Matplotlib by name.

The universal registry instance is matplotlib.colormaps. There should be no need for users to instantiate ColormapRegistry themselves.

Read access uses a dict-like interface mapping names to Colormaps:

import matplotlib as mpl
cmap = mpl.colormaps['viridis']

Returned Colormaps are copies, so that their modification does not change the global definition of the colormap.

Additional colormaps can be added via ColormapRegistry.register:

mpl.colormaps.register(my_colormap)

Additionally, there are shortcut functions to set builtin colormaps; e.g. plt.viridis() is equivalent to plt.set_cmap('viridis').

matplotlib.pyplot.color_sequences[source]#

Container for sequences of colors that are known to Matplotlib by name.

The universal registry instance is matplotlib.color_sequences. There should be no need for users to instantiate ColorSequenceRegistry themselves.

Read access uses a dict-like interface mapping names to lists of colors:

import matplotlib as mpl
cmap = mpl.color_sequences['tab10']

The returned lists are copies, so that their modification does not change the global definition of the color sequence.

Additional color sequences can be added via ColorSequenceRegistry.register:

mpl.color_sequences.register('rgb', ['r', 'g', 'b'])