Movatterモバイル変換


[0]ホーム

URL:


You are reading an old version of the documentation (v2.0.2). For the latest version seehttps://matplotlib.org/stable/
matplotlib

Navigation


Travis-CI:

Table Of Contents

Related Topics

This Page

Quick search

pyplot

matplotlib.pyplot

Provides a MATLAB-like plotting framework.

pylab combines pyplot with numpy into a single namespace.This is convenient for interactive work, but for programming itis recommended that the namespaces be kept separate, e.g.:

importnumpyasnpimportmatplotlib.pyplotaspltx=np.arange(0,5,0.1);y=np.sin(x)plt.plot(x,y)
matplotlib.pyplot.acorr(x,hold=None,data=None,**kwargs)

Plot the autocorrelation ofx.

Parameters:

x : sequence of scalar

hold : boolean, optional,deprecated, default: True

detrend : callable, optional, default:mlab.detrend_none

x is detrended by thedetrend callable. Default is nonormalization.

normed : boolean, optional, default: True

if True, input vectors are normalised to unit length.

usevlines : boolean, optional, default: True

if True, Axes.vlines is used to plot the vertical lines from theorigin to the acorr. Otherwise, Axes.plot is used.

maxlags : integer, optional, default: 10

number of lags to show. If None, will return all 2 * len(x) - 1lags.

Returns:

(lags, c, line, b) : where:

  • lags are a length 2`maxlags+1 lag vector.
  • c is the 2`maxlags+1 auto correlation vectorI
  • line is aLine2D instance returned byplot.
  • b is the x-axis.
Other Parameters:
 

linestyle :Line2D prop, optional, default: None

Only used if usevlines is False.

marker : string, optional, default: ‘o’

Notes

The cross correlation is performed withnumpy.correlate() withmode = 2.

Examples

xcorr is top graph, andacorr is bottom graph.

(Source code,png,pdf)

../_images/xcorr_demo2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’.
matplotlib.pyplot.angle_spectrum(x,Fs=None,Fc=None,window=None,pad_to=None,sides=None,hold=None,data=None,**kwargs)

Plot the angle spectrum.

Call signature:

angle_spectrum(x,Fs=2,Fc=0,window=mlab.window_hanning,pad_to=None,sides='default',**kwargs)

Compute the angle spectrum (wrapped phase spectrum) ofx.Data is padded to a length ofpad_to and the windowing functionwindow is applied to the signal.

Parameters:

x : 1-D array or sequence

Array or sequence containing the data

Fs : scalar

The sampling frequency (samples per time unit). It is usedto calculate the Fourier frequencies, freqs, in cycles per timeunit. The default value is 2.

window : callable or ndarray

A function or a vector of lengthNFFT. To create windowvectors seewindow_hanning(),window_none(),numpy.blackman(),numpy.hamming(),numpy.bartlett(),scipy.signal(),scipy.signal.get_window(), etc. The default iswindow_hanning(). If a function is passed as theargument, it must take a data segment as an argument andreturn the windowed version of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ]

Specifies which sides of the spectrum to return. Default gives thedefault behavior, which returns one-sided for real data and bothfor complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad_to : integer

The number of points to which the data segment is padded whenperforming the FFT. While not increasing the actual resolution ofthe spectrum (the minimum distance between resolvable peaks),this can give more points in the plot, allowing for moredetail. This corresponds to then parameter in the call to fft().The default is None, which setspad_to equal to the length of theinput signal (i.e. no padding).

Fc : integer

The center frequency ofx (defaults to 0), which offsetsthe x extents of the plot to reflect the frequency range usedwhen a signal is acquired and then filtered and downsampled tobaseband.

**kwargs :

Keyword arguments control theLine2Dproperties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
Returns:

spectrum : 1-D array

The values for the angle spectrum in radians (real valued)

freqs : 1-D array

The frequencies corresponding to the elements inspectrum

line : aLine2D instance

The line created by this function

See also

magnitude_spectrum()
angle_spectrum() plots the magnitudes of the corresponding frequencies.
phase_spectrum()
phase_spectrum() plots the unwrapped version of this function.
specgram()
specgram() can plot the angle spectrum of segments within the signal in a colormap.
In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, the following arguments are replaced bydata[<arg>]: * All arguments with the following names: ‘x’.

Examples

(Source code,png,pdf)

../_images/spectrum_demo2.png
matplotlib.pyplot.annotate(*args,**kwargs)

Annotate the pointxy with texts.

Additional kwargs are passed toText.

Parameters:

s : str

The text of the annotation

xy : iterable

Length 2 sequence specifying the(x,y) point to annotate

xytext : iterable, optional

Length 2 sequence specifying the(x,y) to place the textat. If None, defaults toxy.

xycoords : str, Artist, Transform, callable or tuple, optional

The coordinate system thatxy is given in.

For astr the allowed values are:

PropertyDescription
‘figure points’points from the lower left of the figure
‘figure pixels’pixels from the lower left of the figure
‘figure fraction’fraction of figure from lower left
‘axes points’points from lower left corner of axes
‘axes pixels’pixels from lower left corner of axes
‘axes fraction’fraction of axes from lower left
‘data’use the coordinate system of the object beingannotated (default)
‘polar’(theta,r) if not native ‘data’ coordinates

If aArtist object is passed in the units arefraction if it’s bounding box.

If aTransform object is passedin use that to transformxy to screen coordinates

If a callable it must take aRendererBase object as inputand return aTransform orBbox object

If atuple must be length 2 tuple of str,Artist,Transform or callable objects. The first transform isused for thex coordinate and the second fory.

SeeAdvanced Annotation for more details.

Defaults to'data'

textcoords : str,Artist,Transform, callable or tuple, optional

The coordinate system thatxytext is given, whichmay be different than the coordinate system used forxy.

Allxycoords values are valid as well as the followingstrings:

PropertyDescription
‘offset points’offset (in points) from thexy value
‘offset pixels’offset (in pixels) from thexy value

defaults to the input ofxycoords

arrowprops : dict, optional

If not None, properties used to draw aFancyArrowPatch arrow betweenxy andxytext.

Ifarrowprops does not contain the key'arrowstyle' theallowed keys are:

KeyDescription
widththe width of the arrow in points
headwidththe width of the base of the arrow head in points
headlengththe length of the arrow head in points
shrinkfraction of total length to ‘shrink’ from both ends
?any key tomatplotlib.patches.FancyArrowPatch

If thearrowprops contains the key'arrowstyle' theabove keys are forbidden. The allowed values of'arrowstyle' are:

NameAttrs
'-'None
'->'head_length=0.4,head_width=0.2
'-['widthB=1.0,lengthB=0.2,angleB=None
'|-|'widthA=1.0,widthB=1.0
'-|>'head_length=0.4,head_width=0.2
'<-'head_length=0.4,head_width=0.2
'<->'head_length=0.4,head_width=0.2
'<|-'head_length=0.4,head_width=0.2
'<|-|>'head_length=0.4,head_width=0.2
'fancy'head_length=0.4,head_width=0.4,tail_width=0.4
'simple'head_length=0.5,head_width=0.5,tail_width=0.2
'wedge'tail_width=0.3,shrink_factor=0.5

Valid keys forFancyArrowPatch are:

KeyDescription
arrowstylethe arrow style
connectionstylethe connection style
relposdefault is (0.5, 0.5)
patchAdefault is bounding box of the text
patchBdefault is None
shrinkAdefault is 2 points
shrinkBdefault is 2 points
mutation_scaledefault is text size (in points)
mutation_aspectdefault is 1.
?any key formatplotlib.patches.PathPatch

Defaults to None

annotation_clip : bool, optional

Controls the visibility of the annotation when it goesoutside the axes area.

IfTrue, the annotation will only be drawn when thexy is inside the axes. IfFalse, the annotation willalways be drawn regardless of its position.

The default isNone, which behave asTrue only ifxycoords is “data”.

Returns:

Annotation

matplotlib.pyplot.arrow(x,y,dx,dy,hold=None,**kwargs)

Add an arrow to the axes.

Draws arrow on specified axis from (x,y) to (x +dx,y +dy). Uses FancyArrow patch to construct the arrow.

Parameters:

x : float

X-coordinate of the arrow base

y : float

Y-coordinate of the arrow base

dx : float

Length of arrow along x-coordinate

dy : float

Length of arrow along y-coordinate

Returns:

a : FancyArrow

patches.FancyArrow object

Other Parameters:
 

Optional kwargs (inherited from FancyArrow patch) control the arrow

construction and properties:

Constructor arguments

width: float (default: 0.001)

width of full arrow tail

length_includes_head: [True | False] (default: False)

True if head is to be counted in calculating the length.

head_width: float or None (default: 3*width)

total width of the full arrow head

head_length: float or None (default: 1.5 * head_width)

length of arrow head

shape: [‘full’, ‘left’, ‘right’] (default: ‘full’)

draw the left-half, right-half, or full arrow

overhang: float (default: 0)

fraction that the arrow is swept back (0 overhang meanstriangular shape). Can be negative or greater than one.

head_starts_at_zero: [True | False] (default: False)

if True, the head starts being drawn at coordinate 0instead of ending at coordinate 0.

Other valid kwargs (inherited from :class:`Patch`) are:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or aa[True | False] or None for default
axesanAxes instance
capstyle[‘butt’ | ‘round’ | ‘projecting’]
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
colormatplotlib color spec
containsa callable function
edgecolor or ecmpl color spec, None, ‘none’, or ‘auto’
facecolor or fcmpl color spec, or None for default, or ‘none’ for no color
figureamatplotlib.figure.Figure instance
fill[True | False]
gidan id string
hatch[‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’]
joinstyle[‘miter’ | ‘round’ | ‘bevel’]
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat or None for default
path_effectsunknown
picker[None|float|boolean|callable]
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
visible[True | False]
zorderany number

Notes

The resulting arrow is affected by the axes aspect ratio and limits.This may produce an arrow whose head is not square with its stem. Tocreate an arrow whose head is square with its stem, useannotate() for example:

ax.annotate("",xy=(0.5,0.5),xytext=(0,0),arrowprops=dict(arrowstyle="->"))

Examples

(Source code,png,pdf)

../_images/arrow_demo2.png
matplotlib.pyplot.autoscale(enable=True,axis='both',tight=None)

Autoscale the axis view to the data (toggle).

Convenience method for simple axis view autoscaling.It turns autoscaling on or off, and then,if autoscaling for either axis is on, it performsthe autoscaling on the specified axis or axes.

enable: [True | False | None]
True (default) turns autoscaling on, False turns it off.None leaves the autoscaling state unchanged.
axis: [‘x’ | ‘y’ | ‘both’]
which axis to operate on; default is ‘both’
tight: [True | False | None]
If True, set view limits to data limits;if False, let the locator and margins expand the view limits;if None, use tight scaling if the only artist is an image,otherwise treattight as False.Thetight setting is retained for future autoscalinguntil it is explicitly changed.

Returns None.

matplotlib.pyplot.autumn()

set the default colormap to autumn and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.axes(*args,**kwargs)

Add an axes to the figure.

The axes is added at positionrect specified by:

  • axes() by itself creates a default fullsubplot(111) window axis.
  • axes(rect,facecolor='w') whererect = [left, bottom, width,height] in normalized (0, 1) units.facecolor is the backgroundcolor for the axis, default white.
  • axes(h) whereh is an axes instance makesh the currentaxis. AnAxes instance is returned.
kwargAcceptsDescription
facecolorcolorthe axes background color
frameon[True|False]display the frame?
sharexotheraxcurrent axes shares xaxis attributewith otherax
shareyotheraxcurrent axes shares yaxis attributewith otherax
polar[True|False]use a polar axes?
aspect[str | num][‘equal’, ‘auto’] or a number. If a numberthe ratio of x-unit/y-unit in screen-space.Also seeset_aspect().

Examples:

  • examples/pylab_examples/axes_demo.py places custom axes.
  • examples/pylab_examples/shared_axis_demo.py usessharex andsharey.
matplotlib.pyplot.axhline(y=0,xmin=0,xmax=1,hold=None,**kwargs)

Add a horizontal line across the axis.

Parameters:

y : scalar, optional, default: 0

y position in data coordinates of the horizontal line.

xmin : scalar, optional, default: 0

Should be between 0 and 1, 0 being the far left of the plot, 1 thefar right of the plot.

xmax : scalar, optional, default: 1

Should be between 0 and 1, 0 being the far left of the plot, 1 thefar right of the plot.

Returns:

Line2D

See also

axhspan
for example plot and source code

Notes

kwargs are passed toLine2D and can be usedto control the line properties.

Examples

  • draw a thick red hline at ‘y’ = 0 that spans the xrange:

    >>>axhline(linewidth=4,color='r')
  • draw a default hline at ‘y’ = 1 that spans the xrange:

    >>>axhline(y=1)
  • draw a default hline at ‘y’ = .5 that spans the middle half ofthe xrange:

    >>>axhline(y=.5,xmin=0.25,xmax=0.75)

Valid kwargs areLine2D properties,with the exception of ‘transform’:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
matplotlib.pyplot.axhspan(ymin,ymax,xmin=0,xmax=1,hold=None,**kwargs)

Add a horizontal span (rectangle) across the axis.

Draw a horizontal span (rectangle) fromymin toymax.With the default values ofxmin = 0 andxmax = 1, thisalways spans the xrange, regardless of the xlim settings, evenif you change them, e.g., with theset_xlim() command.That is, the horizontal extent is in axes coords: 0=left,0.5=middle, 1.0=right but they location is in datacoordinates.

Parameters:

ymin : float

Lower limit of the horizontal span in data units.

ymax : float

Upper limit of the horizontal span in data units.

xmin : float, optional, default: 0

Lower limit of the vertical span in axes (relative0-1) units.

xmax : float, optional, default: 1

Upper limit of the vertical span in axes (relative0-1) units.

Returns:

Polygon :Polygon

Other Parameters:
 

kwargs :Polygon properties.

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or aa[True | False] or None for default
axesanAxes instance
capstyle[‘butt’ | ‘round’ | ‘projecting’]
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
colormatplotlib color spec
containsa callable function
edgecolor or ecmpl color spec, None, ‘none’, or ‘auto’
facecolor or fcmpl color spec, or None for default, or ‘none’ for no color
figureamatplotlib.figure.Figure instance
fill[True | False]
gidan id string
hatch[‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’]
joinstyle[‘miter’ | ‘round’ | ‘bevel’]
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat or None for default
path_effectsunknown
picker[None|float|boolean|callable]
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
visible[True | False]
zorderany number

See also

axvspan
Add a vertical span (rectangle) across the axes.

Examples

(Source code,png,pdf)

../_images/axhspan_demo2.png
matplotlib.pyplot.axis(*v,**kwargs)

Convenience method to get or set axis properties.

Calling with no arguments:

>>>axis()

returns the current axes limits[xmin,xmax,ymin,ymax].:

>>>axis(v)

sets the min and max of the x and y axes, withv=[xmin,xmax,ymin,ymax].:

>>>axis('off')

turns off the axis lines and labels.:

>>>axis('equal')

changes limits ofx ory axis so that equal increments ofxandy have the same length; a circle is circular.:

>>>axis('scaled')

achieves the same result by changing the dimensions of the plot box insteadof the axis data limits.:

>>>axis('tight')

changesx andy axis limits such that all data is shown. Ifall data is already shown, it will move it to the center of thefigure without modifying (xmax -xmin) or (ymax -ymin). Note this is slightly different than in MATLAB.:

>>>axis('image')

is ‘scaled’ with the axis limits equal to the data limits.:

>>>axis('auto')

and:

>>>axis('normal')

are deprecated. They restore default behavior; axis limits are automaticallyscaled to make the data fit comfortably within the plot box.

iflen(*v)==0, you can pass inxmin,xmax,ymin,ymaxas kwargs selectively to alter just those limits without changingthe others.

>>>axis('square')

changes the limit ranges (xmax-xmin) and (ymax-ymin) ofthex andy axes to be the same, and have the same scaling,resulting in a square plot.

The xmin, xmax, ymin, ymax tuple is returned

See also

xlim(),ylim()
For setting the x- and y-limits individually.
matplotlib.pyplot.axvline(x=0,ymin=0,ymax=1,hold=None,**kwargs)

Add a vertical line across the axes.

Parameters:

x : scalar, optional, default: 0

x position in data coordinates of the vertical line.

ymin : scalar, optional, default: 0

Should be between 0 and 1, 0 being the bottom of the plot, 1 thetop of the plot.

ymax : scalar, optional, default: 1

Should be between 0 and 1, 0 being the bottom of the plot, 1 thetop of the plot.

Returns:

Line2D

See also

axhspan
for example plot and source code

Examples

  • draw a thick red vline atx = 0 that spans the yrange:

    >>>axvline(linewidth=4,color='r')
  • draw a default vline atx = 1 that spans the yrange:

    >>>axvline(x=1)
  • draw a default vline atx = .5 that spans the middle half ofthe yrange:

    >>>axvline(x=.5,ymin=0.25,ymax=0.75)

Valid kwargs areLine2D properties,with the exception of ‘transform’:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
matplotlib.pyplot.axvspan(xmin,xmax,ymin=0,ymax=1,hold=None,**kwargs)

Add a vertical span (rectangle) across the axes.

Draw a vertical span (rectangle) fromxmin toxmax. Withthe default values ofymin = 0 andymax = 1. This alwaysspans the yrange, regardless of the ylim settings, even if youchange them, e.g., with theset_ylim() command. That is,the vertical extent is in axes coords: 0=bottom, 0.5=middle,1.0=top but the y location is in data coordinates.

Parameters:

xmin : scalar

Number indicating the first X-axis coordinate of the verticalspan rectangle in data units.

xmax : scalar

Number indicating the second X-axis coordinate of the verticalspan rectangle in data units.

ymin : scalar, optional

Number indicating the first Y-axis coordinate of the verticalspan rectangle in relative Y-axis units (0-1). Default to 0.

ymax : scalar, optional

Number indicating the second Y-axis coordinate of the verticalspan rectangle in relative Y-axis units (0-1). Default to 1.

Returns:

rectangle : matplotlib.patches.Polygon

Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax).

Other Parameters:
 

**kwargs

Optional parameters are properties of the classmatplotlib.patches.Polygon.

See also

axhspan

Examples

Draw a vertical, green, translucent rectangle from x = 1.25 tox = 1.55 that spans the yrange of the axes.

>>>axvspan(1.25,1.55,facecolor='g',alpha=0.5)
matplotlib.pyplot.bar(left,height,width=0.8,bottom=None,hold=None,data=None,**kwargs)

Make a bar plot.

Make a bar plot with rectangles bounded by:

left,left +width,bottom,bottom +height
(left, right, bottom and top edges)
Parameters:

left : sequence of scalars

the x coordinates of the left sides of the bars

height : sequence of scalars

the heights of the bars

width : scalar or array-like, optional

the width(s) of the barsdefault: 0.8

bottom : scalar or array-like, optional

the y coordinate(s) of the barsdefault: None

color : scalar or array-like, optional

the colors of the bar faces

edgecolor : scalar or array-like, optional

the colors of the bar edges

linewidth : scalar or array-like, optional

width of bar edge(s). If None, use defaultlinewidth; If 0, don’t draw edges.default: None

tick_label : string or array-like, optional

the tick labels of the barsdefault: None

xerr : scalar or array-like, optional

if not None, will be used to generate errorbar(s) on the bar chartdefault: None

yerr : scalar or array-like, optional

if not None, will be used to generate errorbar(s) on the bar chartdefault: None

ecolor : scalar or array-like, optional

specifies the color of errorbar(s)default: None

capsize : scalar, optional

determines the length in points of the error bar capsdefault: None, which will take the value from theerrorbar.capsizercParam.

error_kw : dict, optional

dictionary of kwargs to be passed to errorbar method.ecolor andcapsize may be specified here rather than as independent kwargs.

align : {‘center’, ‘edge’}, optional

If ‘edge’, aligns bars by their left edges (for vertical bars) andby their bottom edges (for horizontal bars). If ‘center’, interprettheleft argument as the coordinates of the centers of the bars.To align on the align bars on the right edge pass a negativewidth.

orientation : {‘vertical’, ‘horizontal’}, optional

The orientation of the bars.

log : boolean, optional

If true, sets the axis to be log scale.default: False

Returns:

bars : matplotlib.container.BarContainer

Container with all of the bars + errorbars

See also

barh
Plot a horizontal bar plot.

Notes

The optional argumentscolor,edgecolor,linewidth,xerr, andyerr can be either scalars or sequences oflength equal to the number of bars. This enables you to usebar as the basis for stacked bar charts, or candlestick plots.Detail:xerr andyerr are passed directly toerrorbar(), so they can also have shape 2xN forindependent specification of lower and upper errors.

Other optional kwargs:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or aa[True | False] or None for default
axesanAxes instance
capstyle[‘butt’ | ‘round’ | ‘projecting’]
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
colormatplotlib color spec
containsa callable function
edgecolor or ecmpl color spec, None, ‘none’, or ‘auto’
facecolor or fcmpl color spec, or None for default, or ‘none’ for no color
figureamatplotlib.figure.Figure instance
fill[True | False]
gidan id string
hatch[‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’]
joinstyle[‘miter’ | ‘round’ | ‘bevel’]
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat or None for default
path_effectsunknown
picker[None|float|boolean|callable]
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
visible[True | False]
zorderany number

Examples

Example: A stacked bar chart.

(Source code,png,pdf)

../_images/bar_stacked2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘bottom’, ‘color’, ‘ecolor’, ‘edgecolor’, ‘height’, ‘left’, ‘linewidth’, ‘tick_label’, ‘width’, ‘xerr’, ‘yerr’.
matplotlib.pyplot.barbs(*args,**kw)

Plot a 2-D field of barbs.

Call signatures:

barb(U,V,**kw)barb(U,V,C,**kw)barb(X,Y,U,V,**kw)barb(X,Y,U,V,C,**kw)

Arguments:

X,Y:
The x and y coordinates of the barb locations(default is head of barb; seepivot kwarg)
U,V:
Give the x and y components of the barb shaft
C:
An optional array used to map colors to the barbs

All arguments may be 1-D or 2-D arrays or sequences. IfX andYare absent, they will be generated as a uniform grid. IfU andVare 2-D arrays butX andY are 1-D, and iflen(X) andlen(Y)match the column and row dimensions ofU, thenX andY will beexpanded withnumpy.meshgrid().

U,V,C may be masked arrays, but maskedX,Y are notsupported at present.

Keyword arguments:

length:
Length of the barb in points; the other parts of the barbare scaled against this.Default is 9
pivot: [ ‘tip’ | ‘middle’ ]
The part of the arrow that is at the grid point; the arrow rotatesabout this point, hence the namepivot. Default is ‘tip’
barbcolor: [ color | color sequence ]
Specifies the color all parts of the barb except any flags. Thisparameter is analagous to theedgecolor parameter for polygons,which can be used instead. However this parameter will overridefacecolor.
flagcolor: [ color | color sequence ]
Specifies the color of any flags on the barb. This parameter isanalagous to thefacecolor parameter for polygons, which can beused instead. However this parameter will override facecolor. Ifthis is not set (andC has not either) thenflagcolor will beset to matchbarbcolor so that the barb has a uniform color. IfC has been set,flagcolor has no effect.
sizes:

A dictionary of coefficients specifying the ratio of a givenfeature to the length of the barb. Only those values one wishes tooverride need to be included. These features include:

  • ‘spacing’ - space between features (flags, full/half barbs)
  • ‘height’ - height (distance from shaft to top) of a flag orfull barb
  • ‘width’ - width of a flag, twice the width of a full barb
  • ‘emptybarb’ - radius of the circle used for low magnitudes
fill_empty:
A flag on whether the empty barbs (circles) that are drawn shouldbe filled with the flag color. If they are not filled, they willbe drawn such that no color is applied to the center. Default isFalse
rounding:
A flag to indicate whether the vector magnitude should be roundedwhen allocating barb components. If True, the magnitude isrounded to the nearest multiple of the half-barb increment. IfFalse, the magnitude is simply truncated to the next lowestmultiple. Default is True
barb_increments:

A dictionary of increments specifying values to associate withdifferent parts of the barb. Only those values one wishes tooverride need to be included.

  • ‘half’ - half barbs (Default is 5)
  • ‘full’ - full barbs (Default is 10)
  • ‘flag’ - flags (default is 50)
flip_barb:
Either a single boolean flag or an array of booleans. Singleboolean indicates whether the lines and flags should pointopposite to normal for all barbs. An array (which should be thesame size as the other data arrays) indicates whether to flip foreach individual barb. Normal behavior is for the barbs and linesto point right (comes from wind barbs having these features pointtowards low pressure in the Northern Hemisphere.) Default isFalse

Barbs are traditionally used in meteorology as a way to plot the speedand direction of wind observations, but can technically be used toplot any two dimensional vector quantity. As opposed to arrows, whichgive vector magnitude by the length of the arrow, the barbs give morequantitative information about the vector magnitude by putting slantedlines or a triangle for various increments in magnitude, as showschematically below:

:/\    \:/  \    \:/    \    \    \:/      \    \    \:------------------------------

The largest increment is given by a triangle (or “flag”). After thosecome full lines (barbs). The smallest increment is a half line. Thereis only, of course, ever at most 1 half line. If the magnitude issmall and only needs a single half-line and no full lines ortriangles, the half-line is offset from the end of the barb so that itcan be easily distinguished from barbs with a single full line. Themagnitude for the barb shown above would nominally be 65, using thestandard increments of 50, 10, and 5.

linewidths and edgecolors can be used to customize the barb.AdditionalPolyCollection keywordarguments:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
visible[True | False]
zorderany number

Example:

(Source code)

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All positional and all keyword arguments.
matplotlib.pyplot.barh(bottom,width,height=0.8,left=None,hold=None,**kwargs)

Make a horizontal bar plot.

Make a horizontal bar plot with rectangles bounded by:

left,left +width,bottom,bottom +height
(left, right, bottom and top edges)

bottom,width,height, andleft can be either scalarsor sequences

Parameters:

bottom : scalar or array-like

the y coordinate(s) of the bars

width : scalar or array-like

the width(s) of the bars

height : sequence of scalars, optional, default: 0.8

the heights of the bars

left : sequence of scalars

the x coordinates of the left sides of the bars

Returns:

matplotlib.patches.Rectangle instances.

Other Parameters:
 

color : scalar or array-like, optional

the colors of the bars

edgecolor : scalar or array-like, optional

the colors of the bar edges

linewidth : scalar or array-like, optional, default: None

width of bar edge(s). If None, use defaultlinewidth; If 0, don’t draw edges.

tick_label : string or array-like, optional, default: None

the tick labels of the bars

xerr : scalar or array-like, optional, default: None

if not None, will be used to generate errorbar(s) on the bar chart

yerr : scalar or array-like, optional, default: None

if not None, will be used to generate errorbar(s) on the bar chart

ecolor : scalar or array-like, optional, default: None

specifies the color of errorbar(s)

capsize : scalar, optional

determines the length in points of the error bar capsdefault: None, which will take the value from theerrorbar.capsizercParam.

error_kw :

dictionary of kwargs to be passed to errorbar method.ecolor andcapsize may be specified here rather than as independent kwargs.

align : {‘center’, ‘edge’}, optional

If ‘edge’, aligns bars by their left edges (for verticalbars) and by their bottom edges (for horizontal bars). If‘center’, interpret thebottom argument as thecoordinates of the centers of the bars. To align on thealign bars on the top edge pass a negative ‘height’.

log : boolean, optional, default: False

If true, sets the axis to be log scale

See also

bar
Plot a vertical bar plot.

Notes

The optional argumentscolor,edgecolor,linewidth,xerr, andyerr can be either scalars or sequences oflength equal to the number of bars. This enables you to usebar as the basis for stacked bar charts, or candlestick plots.Detail:xerr andyerr are passed directly toerrorbar(), so they can also have shape 2xN forindependent specification of lower and upper errors.

Other optional kwargs:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or aa[True | False] or None for default
axesanAxes instance
capstyle[‘butt’ | ‘round’ | ‘projecting’]
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
colormatplotlib color spec
containsa callable function
edgecolor or ecmpl color spec, None, ‘none’, or ‘auto’
facecolor or fcmpl color spec, or None for default, or ‘none’ for no color
figureamatplotlib.figure.Figure instance
fill[True | False]
gidan id string
hatch[‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’]
joinstyle[‘miter’ | ‘round’ | ‘bevel’]
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat or None for default
path_effectsunknown
picker[None|float|boolean|callable]
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
visible[True | False]
zorderany number
matplotlib.pyplot.bone()

set the default colormap to bone and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.box(on=None)

Turn the axes box on or off.on may be a boolean or a string,‘on’ or ‘off’.

Ifon isNone, toggle state.

matplotlib.pyplot.boxplot(x,notch=None,sym=None,vert=None,whis=None,positions=None,widths=None,patch_artist=None,bootstrap=None,usermedians=None,conf_intervals=None,meanline=None,showmeans=None,showcaps=None,showbox=None,showfliers=None,boxprops=None,labels=None,flierprops=None,medianprops=None,meanprops=None,capprops=None,whiskerprops=None,manage_xticks=True,autorange=False,zorder=None,hold=None,data=None)

Make a box and whisker plot.

Make a box and whisker plot for each column ofx or eachvector in sequencex. The box extends from the lower toupper quartile values of the data, with a line at the median.The whiskers extend from the box to show the range of thedata. Flier points are those past the end of the whiskers.

Parameters:

x : Array or a sequence of vectors.

The input data.

notch : bool, optional (False)

IfTrue, will produce a notched box plot. Otherwise, arectangular boxplot is produced. The notches represent theconfidence interval (CI) around the median. See the entryfor thebootstrap parameter for information regardinghow the locations of the notches are computed.

Note

In cases where the values of the CI are less than thelower quartile or greater than the upper quartile, thenotches will extend beyond the box, giving it adistinctive “flipped” appearance. This is expectedbehavior and consistent with other statisticalvisualization packages.

sym : str, optional

The default symbol for flier points. Enter an empty string(‘’) if you don’t want to show fliers. IfNone, then thefliers default to ‘b+’ If you want more control use theflierprops kwarg.

vert : bool, optional (True)

IfTrue (default), makes the boxes vertical. IfFalse,everything is drawn horizontally.

whis : float, sequence, or string (default = 1.5)

As a float, determines the reach of the whiskers to the beyond thefirst and third quartiles. In other words, where IQR is theinterquartile range (Q3-Q1), the upper whisker will extend tolast datum less thanQ3+whis*IQR). Similarly, the lower whiskerwill extend to the first datum greater thanQ1-whis*IQR.Beyond the whiskers, dataare considered outliers and are plotted as individualpoints. Set this to an unreasonably high value to force thewhiskers to show the min and max values. Alternatively, setthis to an ascending sequence of percentile (e.g., [5, 95])to set the whiskers at specific percentiles of the data.Finally,whis can be the string'range' to force thewhiskers to the min and max of the data.

bootstrap : int, optional

Specifies whether to bootstrap the confidence intervalsaround the median for notched boxplots. Ifbootstrap isNone, no bootstrapping is performed, and notches arecalculated using a Gaussian-based asymptotic approximation(see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, andKendall and Stuart, 1967). Otherwise, bootstrap specifiesthe number of times to bootstrap the median to determine its95% confidence intervals. Values between 1000 and 10000 arerecommended.

usermedians : array-like, optional

An array or sequence whose first dimension (or length) iscompatible withx. This overrides the medians computedby matplotlib for each element ofusermedians that is notNone. When an element ofusermedians is None, the medianwill be computed by matplotlib as normal.

conf_intervals : array-like, optional

Array or sequence whose first dimension (or length) iscompatible withx and whose second dimension is 2. Whenthe an element ofconf_intervals is not None, thenotch locations computed by matplotlib are overridden(providednotch isTrue). When an element ofconf_intervals isNone, the notches are computed by themethod specified by the other kwargs (e.g.,bootstrap).

positions : array-like, optional

Sets the positions of the boxes. The ticks and limits areautomatically set to match the positions. Defaults torange(1,N+1) where N is the number of boxes to be drawn.

widths : scalar or array-like

Sets the width of each box either with a scalar or asequence. The default is 0.5, or0.15*(distancebetweenextremepositions), if that is smaller.

patch_artist : bool, optional (False)

IfFalse produces boxes with the Line2D artist. Otherwise,boxes and drawn with Patch artists.

labels : sequence, optional

Labels for each dataset. Length must be compatible withdimensions ofx.

manage_xticks : bool, optional (True)

If the function should adjust the xlim and xtick locations.

autorange : bool, optional (False)

WhenTrue and the data are distributed such that the 25th and75th percentiles are equal,whis is set to'range' suchthat the whisker ends are at the minimum and maximum of thedata.

meanline : bool, optional (False)

IfTrue (andshowmeans isTrue), will try to renderthe mean as a line spanning the full width of the boxaccording tomeanprops (see below). Not recommended ifshownotches is also True. Otherwise, means will be shownas points.

zorder : scalar, optional (None)

Sets the zorder of the boxplot.

Returns:

result : dict

A dictionary mapping each component of the boxplot to a listof thematplotlib.lines.Line2D instancescreated. That dictionary has the following keys (assumingvertical boxplots):

  • boxes: the main body of the boxplot showing thequartiles and the median’s confidence intervals ifenabled.
  • medians: horizontal lines at the median of each box.
  • whiskers: the vertical lines extending to the mostextreme, non-outlier data points.
  • caps: the horizontal lines at the ends of thewhiskers.
  • fliers: points representing data that extend beyondthe whiskers (fliers).
  • means: points or lines representing the means.
Other Parameters:
 

showcaps : bool, optional (True)

Show the caps on the ends of whiskers.

showbox : bool, optional (True)

Show the central box.

showfliers : bool, optional (True)

Show the outliers beyond the caps.

showmeans : bool, optional (False)

Show the arithmetic means.

capprops : dict, optional (None)

Specifies the style of the caps.

boxprops : dict, optional (None)

Specifies the style of the box.

whiskerprops : dict, optional (None)

Specifies the style of the whiskers.

flierprops : dict, optional (None)

Specifies the style of the fliers.

medianprops : dict, optional (None)

Specifies the style of the median.

meanprops : dict, optional (None)

Specifies the style of the mean.

Examples

(Source code,png,pdf)

../_images/boxplot_demo_00_002.png

(png,pdf)

../_images/boxplot_demo_01_002.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All positional and all keyword arguments.
matplotlib.pyplot.broken_barh(xranges,yrange,hold=None,data=None,**kwargs)

Plot horizontal bars.

A collection of horizontal bars spanningyrange with a sequence ofxranges.

Required arguments:

ArgumentDescription
xrangessequence of (xmin,xwidth)
yrangesequence of (ymin,ywidth)

kwargs arematplotlib.collections.BrokenBarHCollectionproperties:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
visible[True | False]
zorderany number

these can either be a single argument, i.e.,:

facecolors='black'

or a sequence of arguments for the various bars, i.e.,:

facecolors=('black','red','green')

Example:

(Source code,png,pdf)

../_images/broken_barh2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All positional and all keyword arguments.
matplotlib.pyplot.cla()

Clear the current axes.

matplotlib.pyplot.clabel(CS,*args,**kwargs)

Label a contour plot.

Call signature:

clabel(cs,**kwargs)

Adds labels to line contours incs, wherecs is aContourSet object returned bycontour.

clabel(cs,v,**kwargs)

only labels contours listed inv.

Optional keyword arguments:

fontsize:
size in points or relative size e.g., ‘smaller’, ‘x-large’
colors:
  • ifNone, the color of each label matches the color ofthe corresponding contour
  • if one string color, e.g.,colors = ‘r’ orcolors =‘red’, all labels will be plotted in this color
  • if a tuple of matplotlib color args (string, float, rgb, etc),different labels will be plotted in different colors in the orderspecified
inline:
controls whether the underlying contour is removed ornot. Default isTrue.
inline_spacing:
space in pixels to leave on each side of label whenplacing inline. Defaults to 5. This spacing will beexact for labels at locations where the contour isstraight, less so for labels on curved contours.
fmt:
a format string for the label. Default is ‘%1.3f’Alternatively, this can be a dictionary matching contourlevels with arbitrary strings to use for each contour level(i.e., fmt[level]=string), or it can be any callable, suchas aFormatter instance, thatreturns a string when called with a numeric contour level.
manual:

ifTrue, contour labels will be placed manually usingmouse clicks. Click the first button near a contour toadd a label, click the second button (or potentially bothmouse buttons at once) to finish adding labels. The thirdbutton can be used to remove the last label added, butonly if labels are not inline. Alternatively, the keyboardcan be used to select label locations (enter to end labelplacement, delete or backspace act like the third mouse button,and any other key will select a label location).

manual can be an iterable object of x,y tuples. Contour labelswill be created as if mouse is clicked at each x,y positions.

rightside_up:
ifTrue (default), label rotations will always be plusor minus 90 degrees from level.
use_clabeltext:
ifTrue (default is False), ClabelText class (instead ofmatplotlib.Text) is used to create labels. ClabelTextrecalculates rotation angles of texts during the drawing time,therefore this can be used if aspect of the axes changes.

(Source code)

matplotlib.pyplot.clf()

Clear the current figure.

matplotlib.pyplot.clim(vmin=None,vmax=None)

Set the color limits of the current image.

To apply clim to all axes images do:

clim(0,0.5)

If eithervmin orvmax is None, the image min/max respectivelywill be used for color scaling.

If you want to set the clim of multiple images,use, for example:

forimingca().get_images():im.set_clim(0,0.05)
matplotlib.pyplot.close(*args)

Close a figure window.

close() by itself closes the current figure

close(h) whereh is aFigure instance, closes that figure

close(num) closes figure numbernum

close(name) wherename is a string, closes figure with that label

close('all') closes all the figure windows

matplotlib.pyplot.cohere(x,y,NFFT=256,Fs=2,Fc=0,detrend=<function detrend_none>,window=<function window_hanning>,noverlap=0,pad_to=None,sides='default',scale_by_freq=None,hold=None,data=None,**kwargs)

Plot the coherence betweenx andy.

Plot the coherence betweenx andy. Coherence is thenormalized cross spectral density:

Parameters:

Fs : scalar

The sampling frequency (samples per time unit). It is usedto calculate the Fourier frequencies, freqs, in cycles per timeunit. The default value is 2.

window : callable or ndarray

A function or a vector of lengthNFFT. To create windowvectors seewindow_hanning(),window_none(),numpy.blackman(),numpy.hamming(),numpy.bartlett(),scipy.signal(),scipy.signal.get_window(), etc. The default iswindow_hanning(). If a function is passed as theargument, it must take a data segment as an argument andreturn the windowed version of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ]

Specifies which sides of the spectrum to return. Default gives thedefault behavior, which returns one-sided for real data and bothfor complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad_to : integer

The number of points to which the data segment is padded whenperforming the FFT. This can be different fromNFFT, whichspecifies the number of data points used. While not increasingthe actual resolution of the spectrum (the minimum distance betweenresolvable peaks), this can give more points in the plot,allowing for more detail. This corresponds to then parameterin the call to fft(). The default is None, which setspad_toequal toNFFT

NFFT : integer

The number of data points used in each block for the FFT.A power 2 is most efficient. The default value is 256.This shouldNOT be used to get zero padding, or the scaling of theresult will be incorrect. Usepad_to for this instead.

detrend : {‘default’, ‘constant’, ‘mean’, ‘linear’, ‘none’} or callable

The function applied to each segment before fft-ing,designed to remove the mean or linear trend. Unlike inMATLAB, where thedetrend parameter is a vector, inmatplotlib is it a function. Thepylabmodule definesdetrend_none(),detrend_mean(), anddetrend_linear(), but you can usea custom function as well. You can also use a string to chooseone of the functions. ‘default’, ‘constant’, and ‘mean’ calldetrend_mean(). ‘linear’ callsdetrend_linear(). ‘none’ callsdetrend_none().

scale_by_freq : boolean, optional

Specifies whether the resulting density values should be scaledby the scaling frequency, which gives density in units of Hz^-1.This allows for integration over the returned frequency values.The default is True for MATLAB compatibility.

noverlap : integer

The number of points of overlap between blocks. Thedefault value is 0 (no overlap).

Fc : integer

The center frequency ofx (defaults to 0), which offsetsthe x extents of the plot to reflect the frequency range usedwhen a signal is acquired and then filtered and downsampled tobaseband.

**kwargs :

Keyword arguments control theLine2Dproperties of the coherence plot:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
Returns:

The return value is a tuple (Cxy,f), wheref are the

frequencies of the coherence vector.

kwargs are applied to the lines.

References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures,John Wiley & Sons (1986)

Examples

(Source code,png,pdf)

../_images/cohere_demo2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’, ‘y’.
matplotlib.pyplot.colorbar(mappable=None,cax=None,ax=None,**kw)

Add a colorbar to a plot.

Function signatures for thepyplot interface; allbut the first are also method signatures for thecolorbar() method:

colorbar(**kwargs)colorbar(mappable,**kwargs)colorbar(mappable,cax=cax,**kwargs)colorbar(mappable,ax=ax,**kwargs)

arguments:

mappable
theImage,ContourSet, etc. towhich the colorbar applies; this argument is mandatory for thecolorbar() method but optional for thecolorbar() function, which sets thedefault to the current image.

keyword arguments:

cax
None | axes object into which the colorbar will be drawn
ax
None | parent axes object(s) from which space for a newcolorbar axes will be stolen. If a list of axes is giventhey will all be resized to make room for the colorbar axes.
use_gridspec
False | Ifcax is None, a newcax is created as an instance ofAxes. Ifax is an instance of Subplot anduse_gridspec is True,cax is created as an instance of Subplot using thegrid_spec module.

Additional keyword arguments are of two kinds:

axes properties:

PropertyDescription
orientationvertical or horizontal
fraction0.15; fraction of original axes to use for colorbar
pad0.05 if vertical, 0.15 if horizontal; fractionof original axes between colorbar and new image axes
shrink1.0; fraction by which to shrink the colorbar
aspect20; ratio of long to short dimensions
anchor(0.0, 0.5) if vertical; (0.5, 1.0) if horizontal;the anchor point of the colorbar axes
panchor(1.0, 0.5) if vertical; (0.5, 0.0) if horizontal;the anchor point of the colorbar parent axes. IfFalse, the parent axes’ anchor will be unchanged

colorbar properties:

PropertyDescription
extend[ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]If not ‘neither’, make pointed end(s) for out-of-range values. These are set for a given colormapusing the colormap set_under and set_over methods.
extendfrac[None | ‘auto’ | length | lengths ]If set toNone, both the minimum and maximumtriangular colorbar extensions with have a length of5% of the interior colorbar length (this is thedefault setting). If set to ‘auto’, makes thetriangular colorbar extensions the same lengths asthe interior boxes (whenspacing is set to‘uniform’) or the same lengths as the respectiveadjacent interior boxes (whenspacing is set to‘proportional’). If a scalar, indicates the lengthof both the minimum and maximum triangular colorbarextensions as a fraction of the interior colorbarlength. A two-element sequence of fractions may alsobe given, indicating the lengths of the minimum andmaximum colorbar extensions respectively as afraction of the interior colorbar length.
extendrect[False |True ]IfFalse the minimum and maximum colorbar extensionswill be triangular (the default). IfTrue theextensions will be rectangular.
spacing[ ‘uniform’ | ‘proportional’ ]Uniform spacing gives each discrete color the samespace; proportional makes the space proportional tothe data interval.
ticks[ None | list of ticks | Locator object ]If None, ticks are determined automatically from theinput.
format[ None | format string | Formatter object ]If None, theScalarFormatter is used.If a format string is given, e.g., ‘%.3f’, that isused. An alternativeFormatter object may begiven instead.
drawedges[ False | True ] If true, draw lines at colorboundaries.

The following will probably be useful only in the context ofindexed colors (that is, when the mappable has norm=NoNorm()),or other unusual circumstances.

PropertyDescription
boundariesNone or a sequence
valuesNone or a sequence which must be of length 1 lessthan the sequence ofboundaries. For each regiondelimited by adjacent entries inboundaries, thecolor mapped to the corresponding value in valueswill be used.

Ifmappable is aContourSet, itsextendkwarg is included automatically.

Note that theshrink kwarg provides a simple way to keep a verticalcolorbar, for example, from being taller than the axes of the mappableto which the colorbar is attached; but it is a manual method requiringsome trial and error. If the colorbar is too tall (or a horizontalcolorbar is too wide) use a smaller value ofshrink.

For more precise control, you can manually specify the positions ofthe axes objects in which the mappable and the colorbar are drawn. Inthis case, do not use any of the axes properties kwargs.

It is known that some vector graphics viewer (svg and pdf) renders white gapsbetween segments of the colorbar. This is due to bugs in the viewers notmatplotlib. As a workaround the colorbar can be rendered with overlappingsegments:

cbar=colorbar()cbar.solids.set_edgecolor("face")draw()

However this has negative consequences in other circumstances. Particularlywith semi transparent images (alpha < 1) and colorbar extensions and is notenabled by default see (issue #1188).

returns:
Colorbar instance; see also its base class,ColorbarBase. Call theset_label() methodto label the colorbar.
matplotlib.pyplot.colors()

This is a do-nothing function to provide you with help on howmatplotlib handles colors.

Commands which take color arguments can use several formats tospecify the colors. For the basic built-in colors, you can use asingle letter

AliasColor
‘b’blue
‘g’green
‘r’red
‘c’cyan
‘m’magenta
‘y’yellow
‘k’black
‘w’white

For a greater range of colors, you have two options. You canspecify the color using an html hex string, as in:

color='#eeefff'

or you can pass an R,G,B tuple, where each of R,G,B are in therange [0,1].

You can also use any legal html name for a color, for example:

color='red'color='burlywood'color='chartreuse'

The example below creates a subplot with a darkslate gray background:

subplot(111,facecolor=(0.1843,0.3098,0.3098))

Here is an example that creates a pale turquoise title:

title('Is this the best color?',color='#afeeee')
matplotlib.pyplot.connect(s,func)

Connect event with strings tofunc. The signature offunc is:

deffunc(event)

where event is amatplotlib.backend_bases.Event. Thefollowing events are recognized

  • ‘button_press_event’
  • ‘button_release_event’
  • ‘draw_event’
  • ‘key_press_event’
  • ‘key_release_event’
  • ‘motion_notify_event’
  • ‘pick_event’
  • ‘resize_event’
  • ‘scroll_event’
  • ‘figure_enter_event’,
  • ‘figure_leave_event’,
  • ‘axes_enter_event’,
  • ‘axes_leave_event’
  • ‘close_event’

For the location events (button and key press/release), if themouse is over the axes, the variableevent.inaxes will beset to theAxes the event occurs isover, and additionally, the variablesevent.xdata andevent.ydata will be defined. This is the mouse locationin data coords. SeeKeyEvent andMouseEvent for more info.

Return value is a connection id that can be used withmpl_disconnect().

Example usage:

defon_press(event):print('you pressed',event.button,event.xdata,event.ydata)cid=canvas.mpl_connect('button_press_event',on_press)
matplotlib.pyplot.contour(*args,**kwargs)

Plot contours.

contour() andcontourf() draw contour lines andfilled contours, respectively. Except as noted, functionsignatures and return values are the same for both versions.

contourf() differs from the MATLABversion in that it does not draw the polygon edges.To draw edges, add line contours withcalls tocontour().

Call signatures:

contour(Z)

make a contour plot of an arrayZ. The level values are chosenautomatically.

contour(X,Y,Z)

X,Y specify the (x, y) coordinates of the surface

contour(Z,N)contour(X,Y,Z,N)

contour up toN automatically-chosen levels.

contour(Z,V)contour(X,Y,Z,V)

draw contour lines at the values specified in sequenceV,which must be in increasing order.

contourf(...,V)

fill thelen(V)-1 regions between the values inV,which must be in increasing order.

contour(Z,**kwargs)

Use keyword args to control colors, linewidth, origin, cmap ... seebelow for more details.

X andY must both be 2-D with the same shape asZ, or theymust both be 1-D such thatlen(X) is the number of columns inZ andlen(Y) is the number of rows inZ.

C=contour(...) returns aQuadContourSet object.

Optional keyword arguments:

corner_mask: [True |False | ‘legacy’ ]

Enable/disable corner masking, which only has an effect ifZ isa masked array. IfFalse, any quad touching a masked point ismasked out. IfTrue, only the triangular corners of quadsnearest those points are always masked out, other triangularcorners comprising three unmasked points are contoured as usual.If ‘legacy’, the old contouring algorithm is used, which isequivalent toFalse and is deprecated, only remaining whilst thenew algorithm is tested fully.

If not specified, the default is taken fromrcParams[‘contour.corner_mask’], which is True unless it hasbeen modified.

colors: [None | string | (mpl_colors) ]

IfNone, the colormap specified by cmap will be used.

If a string, like ‘r’ or ‘red’, all levels will be plotted in thiscolor.

If a tuple of matplotlib color args (string, float, rgb, etc),different levels will be plotted in different colors in the orderspecified.

alpha: float
The alpha blending value
cmap: [None | Colormap ]
A cmColormap instance orNone. Ifcmap isNone andcolors isNone, adefault Colormap is used.
norm: [None | Normalize ]
Amatplotlib.colors.Normalize instance forscaling data values to colors. Ifnorm isNone andcolors isNone, the default linear scaling is used.
vmin,vmax: [None | scalar ]
If notNone, either or both of these values will besupplied to thematplotlib.colors.Normalizeinstance, overriding the default color scaling based onlevels.
levels: [level0, level1, ..., leveln]
A list of floating point numbers indicating the levelcurves to draw, in increasing order; e.g., to draw justthe zero contour passlevels=[0]
origin: [None | ‘upper’ | ‘lower’ | ‘image’ ]

IfNone, the first value ofZ will correspond to thelower left corner, location (0,0). If ‘image’, the rcvalue forimage.origin will be used.

This keyword is not active ifX andY are specified inthe call to contour.

extent: [None | (x0,x1,y0,y1) ]

Iforigin is notNone, thenextent is interpreted asinmatplotlib.pyplot.imshow(): it gives the outerpixel boundaries. In this case, the position of Z[0,0]is the center of the pixel, not a corner. Iforigin isNone, then (x0,y0) is the position of Z[0,0], and(x1,y1) is the position of Z[-1,-1].

This keyword is not active ifX andY are specified inthe call to contour.

locator: [None | ticker.Locator subclass ]
Iflocator isNone, the defaultMaxNLocator is used. Thelocator is used to determine the contour levels if theyare not given explicitly via theV argument.
extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
Unless this is ‘neither’, contour levels are automaticallyadded to one or both ends of the range so that all dataare included. These added ranges are then mapped to thespecial colormap values which default to the ends of thecolormap range, but can be set viamatplotlib.colors.Colormap.set_under() andmatplotlib.colors.Colormap.set_over() methods.
xunits,yunits: [None | registered units ]
Override axis units by specifying an instance of amatplotlib.units.ConversionInterface.
antialiased: [True |False ]
enable antialiasing, overriding the defaults. Forfilled contours, the default isTrue. For line contours,it is taken from rcParams[‘lines.antialiased’].
nchunk: [ 0 | integer ]
If 0, no subdivision of the domain. Specify a positive integer todivide the domain into subdomains ofnchunk bynchunk quads.Chunking reduces the maximum length of polygons generated by thecontouring algorithm which reduces the rendering workload passedon to the backend and also requires slightly less RAM. It canhowever introduce rendering artifacts at chunk boundaries dependingon the backend, theantialiased flag and value ofalpha.

contour-only keyword arguments:

linewidths: [None | number | tuple of numbers ]

Iflinewidths isNone, the default width inlines.linewidth inmatplotlibrc is used.

If a number, all levels will be plotted with this linewidth.

If a tuple, different levels will be plotted with differentlinewidths in the order specified.

linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ]

Iflinestyles isNone, the default is ‘solid’ unlessthe lines are monochrome. In that case, negativecontours will take their linestyle from thematplotlibrccontour.negative_linestyle setting.

linestyles can also be an iterable of the above stringsspecifying a set of linestyles to be used. If thisiterable is shorter than the number of contour levelsit will be repeated as necessary.

contourf-only keyword arguments:

hatches:
A list of cross hatch patterns to use on the filled areas.If None, no hatching will be added to the contour.Hatching is supported in the PostScript, PDF, SVG and Aggbackends only.

Note: contourf fills intervals that are closed at the top; thatis, for boundariesz1 andz2, the filled region is:

z1<z<=z2

There is one exception: if the lowest boundary coincides withthe minimum value of thez array, then that minimum valuewill be included in the lowest interval.

Examples:

(Source code)

(Source code)

(Source code,png,pdf)

../_images/contour_corner_mask3.png
matplotlib.pyplot.contourf(*args,**kwargs)

Plot contours.

contour() andcontourf() draw contour lines andfilled contours, respectively. Except as noted, functionsignatures and return values are the same for both versions.

contourf() differs from the MATLABversion in that it does not draw the polygon edges.To draw edges, add line contours withcalls tocontour().

Call signatures:

contour(Z)

make a contour plot of an arrayZ. The level values are chosenautomatically.

contour(X,Y,Z)

X,Y specify the (x, y) coordinates of the surface

contour(Z,N)contour(X,Y,Z,N)

contour up toN automatically-chosen levels.

contour(Z,V)contour(X,Y,Z,V)

draw contour lines at the values specified in sequenceV,which must be in increasing order.

contourf(...,V)

fill thelen(V)-1 regions between the values inV,which must be in increasing order.

contour(Z,**kwargs)

Use keyword args to control colors, linewidth, origin, cmap ... seebelow for more details.

X andY must both be 2-D with the same shape asZ, or theymust both be 1-D such thatlen(X) is the number of columns inZ andlen(Y) is the number of rows inZ.

C=contour(...) returns aQuadContourSet object.

Optional keyword arguments:

corner_mask: [True |False | ‘legacy’ ]

Enable/disable corner masking, which only has an effect ifZ isa masked array. IfFalse, any quad touching a masked point ismasked out. IfTrue, only the triangular corners of quadsnearest those points are always masked out, other triangularcorners comprising three unmasked points are contoured as usual.If ‘legacy’, the old contouring algorithm is used, which isequivalent toFalse and is deprecated, only remaining whilst thenew algorithm is tested fully.

If not specified, the default is taken fromrcParams[‘contour.corner_mask’], which is True unless it hasbeen modified.

colors: [None | string | (mpl_colors) ]

IfNone, the colormap specified by cmap will be used.

If a string, like ‘r’ or ‘red’, all levels will be plotted in thiscolor.

If a tuple of matplotlib color args (string, float, rgb, etc),different levels will be plotted in different colors in the orderspecified.

alpha: float
The alpha blending value
cmap: [None | Colormap ]
A cmColormap instance orNone. Ifcmap isNone andcolors isNone, adefault Colormap is used.
norm: [None | Normalize ]
Amatplotlib.colors.Normalize instance forscaling data values to colors. Ifnorm isNone andcolors isNone, the default linear scaling is used.
vmin,vmax: [None | scalar ]
If notNone, either or both of these values will besupplied to thematplotlib.colors.Normalizeinstance, overriding the default color scaling based onlevels.
levels: [level0, level1, ..., leveln]
A list of floating point numbers indicating the levelcurves to draw, in increasing order; e.g., to draw justthe zero contour passlevels=[0]
origin: [None | ‘upper’ | ‘lower’ | ‘image’ ]

IfNone, the first value ofZ will correspond to thelower left corner, location (0,0). If ‘image’, the rcvalue forimage.origin will be used.

This keyword is not active ifX andY are specified inthe call to contour.

extent: [None | (x0,x1,y0,y1) ]

Iforigin is notNone, thenextent is interpreted asinmatplotlib.pyplot.imshow(): it gives the outerpixel boundaries. In this case, the position of Z[0,0]is the center of the pixel, not a corner. Iforigin isNone, then (x0,y0) is the position of Z[0,0], and(x1,y1) is the position of Z[-1,-1].

This keyword is not active ifX andY are specified inthe call to contour.

locator: [None | ticker.Locator subclass ]
Iflocator isNone, the defaultMaxNLocator is used. Thelocator is used to determine the contour levels if theyare not given explicitly via theV argument.
extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
Unless this is ‘neither’, contour levels are automaticallyadded to one or both ends of the range so that all dataare included. These added ranges are then mapped to thespecial colormap values which default to the ends of thecolormap range, but can be set viamatplotlib.colors.Colormap.set_under() andmatplotlib.colors.Colormap.set_over() methods.
xunits,yunits: [None | registered units ]
Override axis units by specifying an instance of amatplotlib.units.ConversionInterface.
antialiased: [True |False ]
enable antialiasing, overriding the defaults. Forfilled contours, the default isTrue. For line contours,it is taken from rcParams[‘lines.antialiased’].
nchunk: [ 0 | integer ]
If 0, no subdivision of the domain. Specify a positive integer todivide the domain into subdomains ofnchunk bynchunk quads.Chunking reduces the maximum length of polygons generated by thecontouring algorithm which reduces the rendering workload passedon to the backend and also requires slightly less RAM. It canhowever introduce rendering artifacts at chunk boundaries dependingon the backend, theantialiased flag and value ofalpha.

contour-only keyword arguments:

linewidths: [None | number | tuple of numbers ]

Iflinewidths isNone, the default width inlines.linewidth inmatplotlibrc is used.

If a number, all levels will be plotted with this linewidth.

If a tuple, different levels will be plotted with differentlinewidths in the order specified.

linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ]

Iflinestyles isNone, the default is ‘solid’ unlessthe lines are monochrome. In that case, negativecontours will take their linestyle from thematplotlibrccontour.negative_linestyle setting.

linestyles can also be an iterable of the above stringsspecifying a set of linestyles to be used. If thisiterable is shorter than the number of contour levelsit will be repeated as necessary.

contourf-only keyword arguments:

hatches:
A list of cross hatch patterns to use on the filled areas.If None, no hatching will be added to the contour.Hatching is supported in the PostScript, PDF, SVG and Aggbackends only.

Note: contourf fills intervals that are closed at the top; thatis, for boundariesz1 andz2, the filled region is:

z1<z<=z2

There is one exception: if the lowest boundary coincides withthe minimum value of thez array, then that minimum valuewill be included in the lowest interval.

Examples:

(Source code)

(Source code)

(Source code,png,pdf)

../_images/contour_corner_mask3.png
matplotlib.pyplot.cool()

set the default colormap to cool and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.copper()

set the default colormap to copper and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.csd(x,y,NFFT=None,Fs=None,Fc=None,detrend=None,window=None,noverlap=None,pad_to=None,sides=None,scale_by_freq=None,return_line=None,hold=None,data=None,**kwargs)

Plot the cross-spectral density.

Call signature:

csd(x,y,NFFT=256,Fs=2,Fc=0,detrend=mlab.detrend_none,window=mlab.window_hanning,noverlap=0,pad_to=None,sides='default',scale_by_freq=None,return_line=None,**kwargs)

The cross spectral density by Welch’s averageperiodogram method. The vectorsx andy are divided intoNFFT length segments. Each segment is detrended by functiondetrend and windowed by functionwindow.noverlap givesthe length of the overlap between segments. The product ofthe direct FFTs ofx andy are averaged over each segmentto compute, with a scaling to correct for powerloss due to windowing.

If len(x) <NFFT or len(y) <NFFT, they will be zeropadded toNFFT.

Parameters:

x, y : 1-D arrays or sequences

Arrays or sequences containing the data

Fs : scalar

The sampling frequency (samples per time unit). It is usedto calculate the Fourier frequencies, freqs, in cycles per timeunit. The default value is 2.

window : callable or ndarray

A function or a vector of lengthNFFT. To create windowvectors seewindow_hanning(),window_none(),numpy.blackman(),numpy.hamming(),numpy.bartlett(),scipy.signal(),scipy.signal.get_window(), etc. The default iswindow_hanning(). If a function is passed as theargument, it must take a data segment as an argument andreturn the windowed version of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ]

Specifies which sides of the spectrum to return. Default gives thedefault behavior, which returns one-sided for real data and bothfor complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad_to : integer

The number of points to which the data segment is padded whenperforming the FFT. This can be different fromNFFT, whichspecifies the number of data points used. While not increasingthe actual resolution of the spectrum (the minimum distance betweenresolvable peaks), this can give more points in the plot,allowing for more detail. This corresponds to then parameterin the call to fft(). The default is None, which setspad_toequal toNFFT

NFFT : integer

The number of data points used in each block for the FFT.A power 2 is most efficient. The default value is 256.This shouldNOT be used to get zero padding, or the scaling of theresult will be incorrect. Usepad_to for this instead.

detrend : {‘default’, ‘constant’, ‘mean’, ‘linear’, ‘none’} or callable

The function applied to each segment before fft-ing,designed to remove the mean or linear trend. Unlike inMATLAB, where thedetrend parameter is a vector, inmatplotlib is it a function. Thepylabmodule definesdetrend_none(),detrend_mean(), anddetrend_linear(), but you can usea custom function as well. You can also use a string to chooseone of the functions. ‘default’, ‘constant’, and ‘mean’ calldetrend_mean(). ‘linear’ callsdetrend_linear(). ‘none’ callsdetrend_none().

scale_by_freq : boolean, optional

Specifies whether the resulting density values should be scaledby the scaling frequency, which gives density in units of Hz^-1.This allows for integration over the returned frequency values.The default is True for MATLAB compatibility.

noverlap : integer

The number of points of overlap between segments.The default value is 0 (no overlap).

Fc : integer

The center frequency ofx (defaults to 0), which offsetsthe x extents of the plot to reflect the frequency range usedwhen a signal is acquired and then filtered and downsampled tobaseband.

return_line : bool

Whether to include the line object plotted in the returned values.Default is False.

**kwargs :

Keyword arguments control theLine2Dproperties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
Returns:

Pxy : 1-D array

The values for the cross spectrumP_{xy} before scaling(complex valued)

freqs : 1-D array

The frequencies corresponding to the elements inPxy

line : aLine2D instance

The line created by this function.Only returned ifreturn_line is True.

See also

psd()
psd() is the equivalent to setting y=x.
In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, the following arguments are replaced bydata[<arg>]: * All arguments with the following names: ‘x’, ‘y’.

Notes

For plotting, the power is plotted as for decibels, thoughP_{xy} itselfis returned.

References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures,John Wiley & Sons (1986)

Examples

(Source code,png,pdf)

../_images/csd_demo2.png
matplotlib.pyplot.delaxes(*args)

Remove an axes from the current figure. Ifaxdoesn’t exist, an error will be raised.

delaxes(): delete the current axes

matplotlib.pyplot.disconnect(cid)

Disconnect callback id cid

Example usage:

cid=canvas.mpl_connect('button_press_event',on_press)#...latercanvas.mpl_disconnect(cid)
matplotlib.pyplot.draw()

Redraw the current figure.

This is used to update a figure that has been altered, but notautomatically re-drawn. If interactive mode is on (ion()), thisshould be only rarely needed, but there may be ways to modify the state ofa figure without marking it asstale. Please report these cases asbugs.

A more object-oriented alternative, given anyFigure instance,fig, thatwas created using apyplot function, is:

fig.canvas.draw_idle()
matplotlib.pyplot.errorbar(x,y,yerr=None,xerr=None,fmt='',ecolor=None,elinewidth=None,capsize=None,barsabove=False,lolims=False,uplims=False,xlolims=False,xuplims=False,errorevery=1,capthick=None,hold=None,data=None,**kwargs)

Plot an errorbar graph.

Plot x versus y with error deltas in yerr and xerr.Vertical errorbars are plotted if yerr is not None.Horizontal errorbars are plotted if xerr is not None.

x, y, xerr, and yerr can all be scalars, which plots asingle error bar at x, y.

Parameters:

x : scalar or array-like

y : scalar or array-like

xerr/yerr : scalar or array-like, shape(N,) or shape(2,N), optional

If a scalar number, len(N) array-like object, or a N-elementarray-like object, errorbars are drawn at +/-value relativeto the data. Default is None.

If a sequence of shape 2xN, errorbars are drawn at -row1and +row2 relative to the data.

fmt : plot format string, optional, default: None

The plot format symbol. If fmt is ‘none’ (case-insensitive),only the errorbars are plotted. This is used for addingerrorbars to a bar plot, for example. Default is ‘’,an empty plot format string; properties arethen identical to the defaults forplot().

ecolor : mpl color, optional, default: None

A matplotlib color arg which gives the color the errorbar lines;if None, use the color of the line connecting the markers.

elinewidth : scalar, optional, default: None

The linewidth of the errorbar lines. If None, use the linewidth.

capsize : scalar, optional, default: None

The length of the error bar caps in points; if None, it willtake the value fromerrorbar.capsizercParam.

capthick : scalar, optional, default: None

An alias kwarg to markeredgewidth (a.k.a. - mew). Thissetting is a more sensible name for the property thatcontrols the thickness of the error bar cap in points. Forbackwards compatibility, if mew or markeredgewidth are given,then they will over-ride capthick. This may change in futurereleases.

barsabove : bool, optional, default: False

if True , will plot the errorbars above the plotsymbols. Default is below.

lolims / uplims / xlolims / xuplims : bool, optional, default:None

These arguments can be used to indicate that a value givesonly upper/lower limits. In that case a caret symbol isused to indicate this. lims-arguments may be of the sametype asxerr andyerr. To use limits with invertedaxes,set_xlim() orset_ylim() must be calledbeforeerrorbar().

errorevery : positive integer, optional, default:1

subsamples the errorbars. e.g., if errorevery=5, errorbars forevery 5-th datapoint will be plotted. The data plot itself stillshows all data points.

Returns:

plotline :Line2D instance

x, y plot markers and/or line

caplines : list ofLine2D instances

error bar cap

barlinecols : list ofLineCollection

horizontal and vertical error ranges.

Other Parameters:
 

kwargs : All other keyword arguments are passed on to the plot

command for the markers. For example, this code makes big redsquares with thick green edges:

x,y,yerr=rand(3,10)errorbar(x,y,yerr,marker='s',mfc='red',mec='green',ms=20,mew=4)

where mfc, mec, ms and mew are aliases for the longerproperty names, markerfacecolor, markeredgecolor, markersizeand markeredgewidth.

valid kwargs for the marker properties are

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number

Examples

(Source code,png,pdf)

../_images/errorbar_demo2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’, ‘xerr’, ‘y’, ‘yerr’.
matplotlib.pyplot.eventplot(positions,orientation='horizontal',lineoffsets=1,linelengths=1,linewidths=None,colors=None,linestyles='solid',hold=None,data=None,**kwargs)

Plot identical parallel lines at specific positions.

Plot parallel lines at the given positions. positions should be a 1Dor 2D array-like object, with each row corresponding to a row or columnof lines.

This type of plot is commonly used in neuroscience for representingneural events, where it is commonly called a spike raster, dot raster,or raster plot.

However, it is useful in any situation where you wish to show thetiming or position of multiple sets of discrete events, such as thearrival times of people to a business on each day of the month or thedate of hurricanes each year of the last century.

orientation:[ ‘horizontal’ | ‘vertical’ ]
‘horizontal’ : the lines will be vertical and arranged in rows‘vertical’ : lines will be horizontal and arranged in columns
lineoffsets :
A float or array-like containing floats.
linelengths :
A float or array-like containing floats.
linewidths :
A float or array-like containing floats.
colors
must be a sequence of RGBA tuples (e.g., arbitrary colorstrings, etc, not allowed) or a list of such sequences
linestyles :
[ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] or an array of thesevalues

For linelengths, linewidths, colors, and linestyles, if only a singlevalue is given, that value is applied to all lines. If an array-likeis given, it must have the same length as positions, and each valuewill be applied to the corresponding row or column in positions.

Returns a list ofmatplotlib.collections.EventCollectionobjects that were added.

kwargs areLineCollection properties:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
pathsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
segmentsunknown
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
vertsunknown
visible[True | False]
zorderany number

Example:

(Source code,png,pdf)

../_images/eventplot_demo3.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘colors’, ‘linelengths’, ‘lineoffsets’, ‘linestyles’, ‘linewidths’, ‘positions’.
matplotlib.pyplot.figimage(*args,**kwargs)

Adds a non-resampled image to the figure.

call signatures:

figimage(X,**kwargs)

adds a non-resampled arrayX to the figure.

figimage(X,xo,yo)

with pixel offsetsxo,yo,

X must be a float array:

  • IfX is MxN, assume luminance (grayscale)
  • IfX is MxNx3, assume RGB
  • IfX is MxNx4, assume RGBA

Optional keyword arguments:

KeywordDescription
resizea boolean, True or False. If “True”, then re-size theFigure to match the given image size.
xo or yoAn integer, thex andy image offset in pixels
cmapamatplotlib.colors.Colormap instance, e.g.,cm.jet. IfNone, default to the rcimage.cmapvalue
normamatplotlib.colors.Normalize instance. Thedefault is normalization(). This scales luminance -> 0-1
vmin|vmaxare used to scale a luminance image to 0-1. If eitherisNone, the min and max of the luminance values willbe used. Note if you pass a norm instance, the settingsforvmin andvmax will be ignored.
alphathe alpha blending value, default isNone
origin[ ‘upper’ | ‘lower’ ] Indicates where the [0,0] index ofthe array is in the upper left or lower left corner ofthe axes. Defaults to the rc image.origin value

figimage complements the axes image(imshow()) which will be resampledto fit the current axes. If you want a resampled image tofill the entire figure, you can define anAxes with extent [0,0,1,1].

Anmatplotlib.image.FigureImage instance is returned.

(Source code,png,pdf)

../_images/figimage_demo1.png

Additional kwargs are Artist kwargs passed on toFigureImage

matplotlib.pyplot.figlegend(handles,labels,loc,**kwargs)

Place a legend in the figure.

labels
a sequence of strings
handles
a sequence ofLine2D orPatch instances
loc
can be a string or an integer specifying the legendlocation

Amatplotlib.legend.Legend instance is returned.

Example:

figlegend((line1,line2,line3),('label1','label2','label3'),'upper right')

See also

legend()

matplotlib.pyplot.fignum_exists(num)
matplotlib.pyplot.figtext(*args,**kwargs)

Add text to figure.

Call signature:

text(x,y,s,fontdict=None,**kwargs)

Add text to figure at locationx,y (relative 0-1coords). Seetext() for the meaningof the other arguments.

kwargs control theText properties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
axesanAxes instance
backgroundcolorany matplotlib color
bboxFancyBboxPatch prop dict
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
colorany matplotlib color
containsa callable function
family or fontfamily or fontname or name[FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ]
figureamatplotlib.figure.Figure instance
fontproperties or font_propertiesamatplotlib.font_manager.FontProperties instance
gidan id string
horizontalalignment or ha[ ‘center’ | ‘right’ | ‘left’ ]
labelstring or anything printable with ‘%s’ conversion.
linespacingfloat (multiple of font size)
multialignment[‘left’ | ‘right’ | ‘center’ ]
path_effectsunknown
picker[None|float|boolean|callable]
position(x,y)
rasterized[True | False | None]
rotation[ angle in degrees | ‘vertical’ | ‘horizontal’ ]
rotation_modeunknown
size or fontsize[size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’ ]
sketch_paramsunknown
snapunknown
stretch or fontstretch[a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘condensed’ | ‘semi-condensed’ | ‘normal’ | ‘semi-expanded’ | ‘expanded’ | ‘extra-expanded’ | ‘ultra-expanded’ ]
style or fontstyle[ ‘normal’ | ‘italic’ | ‘oblique’]
textstring or anything printable with ‘%s’ conversion.
transformTransform instance
urla url string
usetexunknown
variant or fontvariant[ ‘normal’ | ‘small-caps’ ]
verticalalignment or ma or va[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
visible[True | False]
weight or fontweight[a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ | ‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ | ‘extra bold’ | ‘black’ ]
wrapunknown
xfloat
yfloat
zorderany number
matplotlib.pyplot.figure(num=None,figsize=None,dpi=None,facecolor=None,edgecolor=None,frameon=True,FigureClass=<class 'matplotlib.figure.Figure'>,**kwargs)

Creates a new figure.

Parameters:

num : integer or string, optional, default: none

If not provided, a new figure will be created, and the figure numberwill be incremented. The figure objects holds this number in anumberattribute.If num is provided, and a figure with this id already exists, makeit active, and returns a reference to it. If this figure does notexists, create it and returns it.If num is a string, the window title will be set to this figure’snum.

figsize : tuple of integers, optional, default: None

width, height in inches. If not provided, defaults to rcfigure.figsize.

dpi : integer, optional, default: None

resolution of the figure. If not provided, defaults to rc figure.dpi.

facecolor :

the background color. If not provided, defaults to rc figure.facecolor

edgecolor :

the border color. If not provided, defaults to rc figure.edgecolor

Returns:

figure : Figure

The Figure instance returned will also be passed to new_figure_managerin the backends, which allows to hook custom Figure classes into thepylab interface. Additional kwargs will be passed to the figure initfunction.

Notes

If you are creating many figures, make sure you explicitly call “close”on the figures you are not using, because this will enable pylabto properly clean up the memory.

rcParams defines the default values, which can be modified in thematplotlibrc file

matplotlib.pyplot.fill(*args,**kwargs)

Plot filled polygons.

Parameters:

args : a variable length argument

It allowing for multiplex,y pairs with an optional color format string; seeplot() for details on the argumentparsing. For example, each of the following is legal:

ax.fill(x,y)ax.fill(x,y,"b")ax.fill(x,y,"b",x,y,"r")

An arbitrary number ofx,y,color groups can be specified::ax.fill(x1, y1, ‘g’, x2, y2, ‘r’)

Returns:

a list ofPatch

Other Parameters:
 

kwargs :Polygon properties

Notes

The same color strings thatplot()supports are supported by the fill format string.

If you would like to fill below a curve, e.g., shade a regionbetween 0 andy alongx, usefill_between()

Examples

(Source code,png,pdf)

../_images/fill_demo3.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’, ‘y’.
matplotlib.pyplot.fill_between(x,y1,y2=0,where=None,interpolate=False,step=None,hold=None,data=None,**kwargs)

Make filled polygons between two curves.

Create aPolyCollectionfilling the regions betweeny1 andy2 wherewhere==True

Parameters:

x : array

An N-length array of the x data

y1 : array

An N-length array (or scalar) of the y data

y2 : array

An N-length array (or scalar) of the y data

where : array, optional

IfNone, default to fill between everywhere. If notNone,it is an N-length numpy boolean array and the fill willonly happen over the regions wherewhere==True.

interpolate : bool, optional

IfTrue, interpolate between the two lines to find theprecise point of intersection. Otherwise, the start andend points of the filled region will only occur on explicitvalues in thex array.

step : {‘pre’, ‘post’, ‘mid’}, optional

If not None, fill with step logic.

See also

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, the following arguments are replaced bydata[<arg>]: * All arguments with the following names: ‘where’, ‘x’, ‘y1’, ‘y2’.

Notes

Additional Keyword args passed on to thePolyCollection.

kwargs control thePolygon properties:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
visible[True | False]
zorderany number

Examples

(Source code)

matplotlib.pyplot.fill_betweenx(y,x1,x2=0,where=None,step=None,hold=None,data=None,**kwargs)

Make filled polygons between two horizontal curves.

Create aPolyCollectionfilling the regions betweenx1 andx2 wherewhere==True

Parameters:

y : array

An N-length array of the y data

x1 : array

An N-length array (or scalar) of the x data

x2 : array, optional

An N-length array (or scalar) of the x data

where : array, optional

IfNone, default to fill between everywhere. If notNone,it is a N length numpy boolean array and the fill willonly happen over the regions wherewhere==True

step : {‘pre’, ‘post’, ‘mid’}, optional

If not None, fill with step logic.

See also

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, the following arguments are replaced bydata[<arg>]: * All arguments with the following names: ‘where’, ‘x1’, ‘x2’, ‘y’.

Notes

keyword args passed on to the
PolyCollection

kwargs control thePolygon properties:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
visible[True | False]
zorderany number

Examples

(Source code)

matplotlib.pyplot.findobj(o=None,match=None,include_self=True)

Find artist objects.

Recursively find allArtist instancescontained in self.

match can be

  • None: return all objects contained in artist.
  • function with signatureboolean=match(artist)used to filter matches
  • class instance: e.g., Line2D. Only return artists of class type.

Ifinclude_self is True (default), include self in the list to bechecked for a match.

matplotlib.pyplot.flag()

set the default colormap to flag and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.gca(**kwargs)

Get the currentAxes instance on thecurrent figure matching the given keyword args, or create one.

See also

matplotlib.figure.Figure.gca
The figure’s gca method.

Examples

To get the current polar axes on the current figure:

plt.gca(projection='polar')

If the current axes doesn’t exist, or isn’t a polar one, the appropriateaxes will be created and then returned.

matplotlib.pyplot.gcf()

Get a reference to the current figure.

matplotlib.pyplot.gci()

Get the current colorable artist. Specifically, returns thecurrentScalarMappable instance (image orpatch collection), orNone if no images or patch collectionshave been defined. The commandsimshow()andfigimage() createImage instances, and the commandspcolor() andscatter() createCollection instances. Thecurrent image is an attribute of the current axes, or the nearestearlier axes in the current figure that contains an image.

matplotlib.pyplot.get_current_fig_manager()
matplotlib.pyplot.get_figlabels()

Return a list of existing figure labels.

matplotlib.pyplot.get_fignums()

Return a list of existing figure numbers.

matplotlib.pyplot.get_plot_commands()

Get a sorted list of all of the plotting commands.

matplotlib.pyplot.ginput(*args,**kwargs)

Blocking call to interact with the figure.

This will wait forn clicks from the user and return a list of thecoordinates of each click.

Iftimeout is zero or negative, does not timeout.

Ifn is zero or negative, accumulate clicks until a middle click(or potentially both mouse buttons at once) terminates the input.

Right clicking cancels last input.

The buttons used for the various actions (adding points, removingpoints, terminating the inputs) can be overriden via theargumentsmouse_add,mouse_pop andmouse_stop, that givethe associated mouse button: 1 for left, 2 for middle, 3 forright.

The keyboard can also be used to select points in case your mousedoes not have one or more of the buttons. The delete and backspacekeys act like right clicking (i.e., remove last point), the enter keyterminates input and any other key (not already used by the windowmanager) selects a point.

matplotlib.pyplot.gray()

set the default colormap to gray and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.grid(b=None,which='major',axis='both',**kwargs)

Turn the axes grids on or off.

Set the axes grids on or off;b is a boolean. (For MATLABcompatibility,b may also be a string, ‘on’ or ‘off’.)

Ifb isNone andlen(kwargs)==0, toggle the grid state. Ifkwargs are supplied, it is assumed that you want a grid andbis thus set toTrue.

which can be ‘major’ (default), ‘minor’, or ‘both’ to controlwhether major tick grids, minor tick grids, or both are affected.

axis can be ‘both’ (default), ‘x’, or ‘y’ to control whichset of gridlines are drawn.

kwargs are used to set the grid line properties, e.g.,:

ax.grid(color='r',linestyle='-',linewidth=2)

ValidLine2D kwargs are

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
matplotlib.pyplot.hexbin(x,y,C=None,gridsize=100,bins=None,xscale='linear',yscale='linear',extent=None,cmap=None,norm=None,vmin=None,vmax=None,alpha=None,linewidths=None,edgecolors='none',reduce_C_function=<function mean>,mincnt=None,marginals=False,hold=None,data=None,**kwargs)

Make a hexagonal binning plot.

Make a hexagonal binning plot ofx versusy, wherex,y are 1-D sequences of the same length,N. IfC isNone(the default), this is a histogram of the number of occurencesof the observations at (x[i],y[i]).

IfC is specified, it specifies values at the coordinate(x[i],y[i]). These values are accumulated for each hexagonalbin and then reduced according toreduce_C_function, whichdefaults to numpy’s mean function (np.mean). (IfC isspecified, it must also be a 1-D sequence of the same lengthasx andy.)

Parameters:

x, y : array or masked array

C : array or masked array, optional, default isNone

gridsize : int or (int, int), optional, default is 100

The number of hexagons in thex-direction, default is100. The corresponding number of hexagons in they-direction is chosen such that the hexagons areapproximately regular. Alternatively, gridsize can be atuple with two elements specifying the number of hexagonsin thex-direction and they-direction.

bins : {‘log’} or int or sequence, optional, default isNone

IfNone, no binning is applied; the color of each hexagondirectly corresponds to its count value.

If ‘log’, use a logarithmic scale for the colormap. Internally, is used todetermine the hexagon color.

If an integer, divide the counts in the specified numberof bins, and color the hexagons accordingly.

If a sequence of values, the values of the lower bound ofthe bins to be used.

xscale : {‘linear’, ‘log’}, optional, default is ‘linear’

Use a linear or log10 scale on the horizontal axis.

yscale : {‘linear’, ‘log’}, optional, default is ‘linear’

Use a linear or log10 scale on the vertical axis.

mincnt : int > 0, optional, default isNone

If notNone, only display cells with more thanmincntnumber of points in the cell

marginals : bool, optional, default isFalse

if marginals isTrue, plot the marginal density ascolormapped rectagles along the bottom of the x-axis andleft of the y-axis

extent : scalar, optional, default isNone

The limits of the bins. The default assigns the limitsbased ongridsize,x,y,xscale andyscale.

Ifxscale oryscale is set to ‘log’, the limits areexpected to be the exponent for a power of 10. E.g. forx-limits of 1 and 50 in ‘linear’ scale and y-limitsof 10 and 1000 in ‘log’ scale, enter (1, 50, 1, 3).

Order of scalars is (left, right, bottom, top).

Returns:

object

aPolyCollection instance; useget_array() onthisPolyCollection to getthe counts in each hexagon.

Ifmarginals isTrue, horizontalbar and vertical bar (both PolyCollections) will be attachedto the return collection as attributeshbar andvbar.

Other Parameters:
 

cmap : object, optional, default isNone

amatplotlib.colors.Colormap instance. IfNone,defaults to rcimage.cmap.

norm : object, optional, default isNone

matplotlib.colors.Normalize instance is used toscale luminance data to 0,1.

vmin, vmax : scalar, optional, default isNone

vmin andvmax are used in conjunction withnorm tonormalize luminance data. IfNone, the min and max of thecolor arrayC are used. Note if you pass a norm instanceyour settings forvmin andvmax will be ignored.

alpha : scalar between 0 and 1, optional, default isNone

the alpha value for the patches

linewidths : scalar, optional, default isNone

IfNone, defaults to 1.0.

edgecolors : {‘none’} or mpl color, optional, default is ‘none’

If ‘none’, draws the edges in the same color as the fill color.This is the default, as it avoids unsightly unpainted pixelsbetween the hexagons.

IfNone, draws outlines in the default color.

If a matplotlib color arg, draws outlines in the specified color.

Notes

The standard descriptions of all theCollection parameters:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
visible[True | False]
zorderany number

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’, ‘y’.

Examples

(Source code,png,pdf)

../_images/hexbin_demo3.png
matplotlib.pyplot.hist(x,bins=None,range=None,normed=False,weights=None,cumulative=False,bottom=None,histtype='bar',align='mid',orientation='vertical',rwidth=None,log=False,color=None,label=None,stacked=False,hold=None,data=None,**kwargs)

Plot a histogram.

Compute and draw the histogram ofx. The return value is atuple (n,bins,patches) or ([n0,n1, ...],bins,[patches0,patches1,...]) if the input contains multipledata.

Multiple data can be provided viax as a list of datasetsof potentially different length ([x0,x1, ...]), or asa 2-D ndarray in which each column is a dataset. Note thatthe ndarray form is transposed relative to the list form.

Masked arrays are not supported at present.

Parameters:

x : (n,) array or sequence of (n,) arrays

Input values, this takes either a single array or a sequency ofarrays which are not required to be of the same length

bins : integer or array_like or ‘auto’, optional

If an integer is given,bins+1 bin edges are returned,consistently withnumpy.histogram() for numpy version >=1.3.

Unequally spaced bins are supported ifbins is a sequence.

If Numpy 1.11 is installed, may also be'auto'.

Default is taken from the rcParamhist.bins.

range : tuple or None, optional

The lower and upper range of the bins. Lower and upper outliersare ignored. If not provided,range is (x.min(), x.max()). Rangehas no effect ifbins is a sequence.

Ifbins is a sequence orrange is specified, autoscalingis based on the specified bin range instead of therange of x.

Default isNone

normed : boolean, optional

IfTrue, the first element of the return tuple willbe the counts normalized to form a probability density, i.e.,n/(len(x)`dbin), i.e., the integral of the histogram will sumto 1. Ifstacked is alsoTrue, the sum of the histograms isnormalized to 1.

Default isFalse

weights : (n, ) array_like or None, optional

An array of weights, of the same shape asx. Each value inxonly contributes its associated weight towards the bin count(instead of 1). Ifnormed is True, the weights are normalized,so that the integral of the density over the range remains 1.

Default isNone

cumulative : boolean, optional

IfTrue, then a histogram is computed where each bin gives thecounts in that bin plus all bins for smaller values. The last bingives the total number of datapoints. Ifnormed is alsoTruethen the histogram is normalized such that the last bin equals 1.Ifcumulative evaluates to less than 0 (e.g., -1), the directionof accumulation is reversed. In this case, ifnormed is alsoTrue, then the histogram is normalized such that the first binequals 1.

Default isFalse

bottom : array_like, scalar, or None

Location of the bottom baseline of each bin. If a scalar,the base line for each bin is shifted by the same amount.If an array, each bin is shifted independently and the lengthof bottom must match the number of bins. If None, defaults to 0.

Default isNone

histtype : {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}, optional

The type of histogram to draw.

  • ‘bar’ is a traditional bar-type histogram. If multiple dataare given the bars are aranged side by side.
  • ‘barstacked’ is a bar-type histogram where multipledata are stacked on top of each other.
  • ‘step’ generates a lineplot that is by defaultunfilled.
  • ‘stepfilled’ generates a lineplot that is by defaultfilled.

Default is ‘bar’

align : {‘left’, ‘mid’, ‘right’}, optional

Controls how the histogram is plotted.

  • ‘left’: bars are centered on the left bin edges.
  • ‘mid’: bars are centered between the bin edges.
  • ‘right’: bars are centered on the right bin edges.

Default is ‘mid’

orientation : {‘horizontal’, ‘vertical’}, optional

If ‘horizontal’,barh will be used forbar-type histograms and thebottom kwarg will be the left edges.

rwidth : scalar or None, optional

The relative width of the bars as a fraction of the bin width. IfNone, automatically compute the width.

Ignored ifhisttype is ‘step’ or ‘stepfilled’.

Default isNone

log : boolean, optional

IfTrue, the histogram axis will be set to a log scale. IflogisTrue andx is a 1D array, empty bins will be filtered outand only the non-empty (n,bins,patches) will be returned.

Default isFalse

color : color or array_like of colors or None, optional

Color spec or sequence of color specs, one per dataset. Default(None) uses the standard line color sequence.

Default isNone

label : string or None, optional

String, or sequence of strings to match multiple datasets. Barcharts yield multiple patches per dataset, but only the first getsthe label, so that the legend command will work as expected.

default isNone

stacked : boolean, optional

IfTrue, multiple data are stacked on top of each other IfFalse multiple data are aranged side by side if histtype is‘bar’ or on top of each other if histtype is ‘step’

Default isFalse

Returns:

n : array or list of arrays

The values of the histogram bins. Seenormed andweightsfor a description of the possible semantics. If inputx is anarray, then this is an array of lengthnbins. If input is asequence arrays[data1,data2,..], then this is a list ofarrays with the values of the histograms for each of the arraysin the same order.

bins : array

The edges of the bins. Length nbins + 1 (nbins left edges and rightedge of last bin). Always a single array even when multiple datasets are passed in.

patches : list or list of lists

Silent list of individual patches used to create the histogramor list of such list if multiple input datasets.

Other Parameters:
 

kwargs :Patch properties

See also

hist2d
2D histograms

Notes

Until numpy release 1.5, the underlying numpy histogram function wasincorrect withnormed`=`True if bin sizes were unequal. MPLinherited that error. It is now corrected within MPL when usingearlier numpy versions.

Examples

(Source code,png,pdf)

../_images/histogram_demo_features3.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘weights’, ‘x’.
matplotlib.pyplot.hist2d(x,y,bins=10,range=None,normed=False,weights=None,cmin=None,cmax=None,hold=None,data=None,**kwargs)

Make a 2D histogram plot.

Parameters:

x, y: array_like, shape (n, )

Input values

bins: [None | int | [int, int] | array_like | [array, array]]

The bin specification:

  • If int, the number of bins for the two dimensions(nx=ny=bins).
  • If [int, int], the number of bins in each dimension(nx, ny = bins).
  • If array_like, the bin edges for the two dimensions(x_edges=y_edges=bins).
  • If [array, array], the bin edges in each dimension(x_edges, y_edges = bins).

The default value is 10.

range : array_like shape(2, 2), optional, default: None

The leftmost and rightmost edges of the bins along each dimension(if not specified explicitly in the bins parameters): [[xmin,xmax], [ymin, ymax]]. All values outside of this range will beconsidered outliers and not tallied in the histogram.

normed : boolean, optional, default: False

Normalize histogram.

weights : array_like, shape (n, ), optional, default: None

An array of values w_i weighing each sample (x_i, y_i).

cmin : scalar, optional, default: None

All bins that has count less than cmin will not be displayed andthese count values in the return value count histogram will alsobe set to nan upon return

cmax : scalar, optional, default: None

All bins that has count more than cmax will not be displayed (setto none before passing to imshow) and these count values in thereturn value count histogram will also be set to nan upon return

Returns:

The return value is(counts,xedges,yedges,Image).

Other Parameters:
 

cmap : {Colormap, string}, optional

Amatplotlib.colors.Colormap instance. If not set, use rcsettings.

norm : Normalize, optional

Amatplotlib.colors.Normalize instance is used toscale luminance data to[0,1]. If not set, defaults toNormalize().

vmin/vmax : {None, scalar}, optional

Arguments passed to theNormalize instance.

alpha :0<=scalar<=1 orNone, optional

The alpha blending value.

See also

hist
1D histogram

Notes

Rendering the histogram with a logarithmic color scale isaccomplished by passing acolors.LogNorm instance tothenorm keyword argument. Likewise, power-law normalization(similar in effect to gamma correction) can be accomplished withcolors.PowerNorm.

Examples

(Source code,png,pdf)

../_images/hist2d_demo2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘weights’, ‘x’, ‘y’.
matplotlib.pyplot.hlines(y,xmin,xmax,colors='k',linestyles='solid',label='',hold=None,data=None,**kwargs)

Plot horizontal lines at eachy fromxmin toxmax.

Parameters:

y : scalar or sequence of scalar

y-indexes where to plot the lines.

xmin, xmax : scalar or 1D array_like

Respective beginning and end of each line. If scalars areprovided, all lines will have same length.

colors : array_like of colors, optional, default: ‘k’

linestyles : [‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’], optional

label : string, optional, default: ‘’

Returns:

lines :LineCollection

Other Parameters:
 

kwargs :LineCollection properties.

See also

vlines
vertical lines

Examples

(Source code,png,pdf)

../_images/vline_hline_demo2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘xmax’, ‘xmin’, ‘y’.
matplotlib.pyplot.hold(b=None)

Deprecated since version 2.0:pyplot.hold is deprecated.Future behavior will be consistent with the long-time default:plot commands add elements without first clearing theAxes and/or Figure.

Set the hold state. Ifb is None (default), toggle thehold state, else set the hold state to boolean valueb:

hold()# toggle holdhold(True)# hold is onhold(False)# hold is off

Whenhold isTrue, subsequent plot commands will add elements tothe current axes. Whenhold isFalse, the current axes andfigure will be cleared on the next plot command.

matplotlib.pyplot.hot()

set the default colormap to hot and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.hsv()

set the default colormap to hsv and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.imread(*args,**kwargs)

Read an image from a file into an array.

fname may be a string path, a valid URL, or a Pythonfile-like object. If using a file object, it must be opened in binarymode.

Ifformat is provided, will try to read file of that type,otherwise the format is deduced from the filename. If nothing canbe deduced, PNG is tried.

Return value is anumpy.array. For grayscale images, thereturn array is MxN. For RGB images, the return value is MxNx3.For RGBA images the return value is MxNx4.

matplotlib can only read PNGs natively, but ifPIL is installed, it willuse it to load the image and return an array (if possible) whichcan be used withimshow(). Note, URL stringsmay not be compatible with PIL. Check the PIL documentation for moreinformation.

matplotlib.pyplot.imsave(*args,**kwargs)

Save an array as in image file.

The output formats available depend on the backend being used.

Arguments:
fname:
A string containing a path to a filename, or a Python file-like object.Ifformat isNone andfname is a string, the outputformat is deduced from the extension of the filename.
arr:
An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array.
Keyword arguments:
vmin/vmax: [ None | scalar ]
vmin andvmax set the color scaling for the image by fixing thevalues that map to the colormap color limits. If eithervminorvmax is None, that limit is determined from thearrmin/max value.
cmap:
cmap is a colors.Colormap instance, e.g., cm.jet.If None, default to the rc image.cmap value.
format:
One of the file extensions supported by the activebackend. Most backends support png, pdf, ps, eps and svg.
origin
[ ‘upper’ | ‘lower’ ] Indicates where the [0,0] index ofthe array is in the upper left or lower left corner ofthe axes. Defaults to the rc image.origin value.
dpi
The DPI to store in the metadata of the file. This does not affect theresolution of the output image.
matplotlib.pyplot.imshow(X,cmap=None,norm=None,aspect=None,interpolation=None,alpha=None,vmin=None,vmax=None,origin=None,extent=None,shape=None,filternorm=1,filterrad=4.0,imlim=None,resample=None,url=None,hold=None,data=None,**kwargs)

Display an image on the axes.

Parameters:

X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)

Display the image inX to current axes.X may be anarray or a PIL image. IfX is an array, itcan have the following shapes and types:

  • MxN – values to be mapped (float or int)
  • MxNx3 – RGB (float or uint8)
  • MxNx4 – RGBA (float or uint8)

The value for each component of MxNx3 and MxNx4 float arraysshould be in the range 0.0 to 1.0. MxN arrays are mappedto colors based on thenorm (mapping scalar to scalar)and thecmap (mapping the normed scalar to a color).

cmap :Colormap, optional, default: None

If None, default to rcimage.cmap value.cmap is ignoredifX is 3-D, directly specifying RGB(A) values.

aspect : [‘auto’ | ‘equal’ | scalar], optional, default: None

If ‘auto’, changes the image aspect ratio to match that of theaxes.

If ‘equal’, andextent is None, changes the axes aspect ratio tomatch that of the image. Ifextent is notNone, the axesaspect ratio is changed to match that of the extent.

If None, default to rcimage.aspect value.

interpolation : string, optional, default: None

Acceptable values are ‘none’, ‘nearest’, ‘bilinear’, ‘bicubic’,‘spline16’, ‘spline36’, ‘hanning’, ‘hamming’, ‘hermite’, ‘kaiser’,‘quadric’, ‘catrom’, ‘gaussian’, ‘bessel’, ‘mitchell’, ‘sinc’,‘lanczos’

Ifinterpolation is None, default to rcimage.interpolation.See also thefilternorm andfilterrad parameters.Ifinterpolation is ‘none’, then no interpolation is performedon the Agg, ps and pdf backends. Other backends will fall back to‘nearest’.

norm :Normalize, optional, default: None

ANormalize instance is used to scalea 2-D floatX input to the (0, 1) range for input to thecmap. Ifnorm is None, use the default func:normalize.Ifnorm is an instance ofNoNorm,X must be an array of integers that index directly intothe lookup table of thecmap.

vmin, vmax : scalar, optional, default: None

vmin andvmax are used in conjunction with norm to normalizeluminance data. Note if you pass anorm instance, yoursettings forvmin andvmax will be ignored.

alpha : scalar, optional, default: None

The alpha blending value, between 0 (transparent) and 1 (opaque)

origin : [‘upper’ | ‘lower’], optional, default: None

Place the [0,0] index of the array in the upper left or lower leftcorner of the axes. If None, default to rcimage.origin.

extent : scalars (left, right, bottom, top), optional, default: None

The location, in data-coordinates, of the lower-left andupper-right corners. IfNone, the image is positioned such thatthe pixel centers fall on zero-based (row, column) indices.

shape : scalars (columns, rows), optional, default: None

For raw buffer images

filternorm : scalar, optional, default: 1

A parameter for the antigrain image resize filter. From theantigrain documentation, iffilternorm = 1, the filternormalizes integer values and corrects the rounding errors. Itdoesn’t do anything with the source floating point values, itcorrects only integers according to the rule of 1.0 which meansthat any sum of pixel weights must be equal to 1.0. So, thefilter function must produce a graph of the proper shape.

filterrad : scalar, optional, default: 4.0

The filter radius for filters that have a radius parameter, i.e.when interpolation is one of: ‘sinc’, ‘lanczos’ or ‘blackman’

Returns:

image :AxesImage

Other Parameters:
 

kwargs :Artist properties.

See also

matshow
Plot a matrix or an array as an image.

Notes

Unlessextent is used, pixel centers will be located at integercoordinates. In other words: the origin will coincide with the centerof pixel (0, 0).

Examples

(Source code,png,pdf)

../_images/image_demo4.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All positional and all keyword arguments.
matplotlib.pyplot.inferno()

set the default colormap to inferno and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.install_repl_displayhook()

Install a repl display hook so that any stale figure are automaticallyredrawn when control is returned to the repl.

This works with IPython terminals and kernels,as well as vanilla python shells.

matplotlib.pyplot.ioff()

Turn interactive mode off.

matplotlib.pyplot.ion()

Turn interactive mode on.

matplotlib.pyplot.ishold()

Deprecated since version 2.0:pyplot.hold is deprecated.Future behavior will be consistent with the long-time default:plot commands add elements without first clearing theAxes and/or Figure.

Return the hold status of the current axes.

matplotlib.pyplot.isinteractive()

Return status of interactive mode.

matplotlib.pyplot.jet()

set the default colormap to jet and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.legend(*args,**kwargs)

Places a legend on the axes.

To make a legend for lines which already exist on the axes(via plot for instance), simply call this function with an iterableof strings, one for each legend item. For example:

ax.plot([1,2,3])ax.legend(['A simple line'])

However, in order to keep the “label” and the legend elementinstance together, it is preferable to specify the label either atartist creation, or by calling theset_label() method on the artist:

line,=ax.plot([1,2,3],label='Inline label')# Overwrite the label by calling the method.line.set_label('Label via method')ax.legend()

Specific lines can be excluded from the automatic legend elementselection by defining a label starting with an underscore.This is default for all artists, so callinglegend() withoutany arguments and without setting the labels manually will result inno legend being drawn.

For full control of which artists have a legend entry, it is possibleto pass an iterable of legend artists followed by an iterable oflegend labels respectively:

legend((line1,line2,line3),('label1','label2','label3'))
Parameters:

loc : int or string or pair of floats, default: ‘upper right’

The location of the legend. Possible codes are:

Location StringLocation Code
‘best’0
‘upper right’1
‘upper left’2
‘lower left’3
‘lower right’4
‘right’5
‘center left’6
‘center right’7
‘lower center’8
‘upper center’9
‘center’10

Alternatively can be a 2-tuple givingx,y of the lower-leftcorner of the legend in axes coordinates (in which casebbox_to_anchor will be ignored).

bbox_to_anchor :matplotlib.transforms.BboxBase instance or tuple of floats

Specify any arbitrary location for the legend inbbox_transformcoordinates (default Axes coordinates).

For example, to put the legend’s upper right hand corner in thecenter of the axes the following keywords can be used:

loc='upper right',bbox_to_anchor=(0.5,0.5)

ncol : integer

The number of columns that the legend has. Default is 1.

prop : None ormatplotlib.font_manager.FontProperties or dict

The font properties of the legend. If None (default), the currentmatplotlib.rcParams will be used.

fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

Controls the font size of the legend. If the value is numeric thesize will be the absolute font size in points. String values arerelative to the current default font size. This argument is onlyused ifprop is not specified.

numpoints : None or int

The number of marker points in the legend when creating a legendentry for a line/matplotlib.lines.Line2D.Default isNone which will take the value from thelegend.numpointsrcParam.

scatterpoints : None or int

The number of marker points in the legend when creating a legendentry for a scatter plot/matplotlib.collections.PathCollection.Default isNone which will take the value from thelegend.scatterpointsrcParam.

scatteryoffsets : iterable of floats

The vertical offset (relative to the font size) for the markerscreated for a scatter plot legend entry. 0.0 is at the base thelegend text, and 1.0 is at the top. To draw all markers at thesame height, set to[0.5]. Default[0.375,0.5,0.3125].

markerscale : None or int or float

The relative size of legend markers compared with the originallydrawn ones. Default isNone which will take the value fromthelegend.markerscalercParam.

markerfirst : bool

ifTrue, legend marker is placed to the left of the legend labelifFalse, legend marker is placed to the right of the legendlabel

frameon : None or bool

Control whether the legend should be drawn on a patch (frame).Default isNone which will take the value from thelegend.frameonrcParam.

fancybox : None or bool

Control whether round edges should be enabled aroundtheFancyBboxPatch whichmakes up the legend’s background.Default isNone which will take the value from thelegend.fancyboxrcParam.

shadow : None or bool

Control whether to draw a shadow behind the legend.Default isNone which will take the value from thelegend.shadowrcParam.

framealpha : None or float

Control the alpha transparency of the legend’s background.Default isNone which will take the value from thelegend.framealpharcParam.

facecolor : None or “inherit” or a color spec

Control the legend’s background color.Default isNone which will take the value from thelegend.facecolorrcParam.If"inherit", it will take theaxes.facecolorrcParam.

edgecolor : None or “inherit” or a color spec

Control the legend’s background patch edge color.Default isNone which will take the value from thelegend.edgecolorrcParam.If"inherit", it will take theaxes.edgecolorrcParam.

mode : {“expand”, None}

Ifmode is set to"expand" the legend will be horizontallyexpanded to fill the axes area (orbbox_to_anchor if definesthe legend’s size).

bbox_transform : None ormatplotlib.transforms.Transform

The transform for the bounding box (bbox_to_anchor). For a valueofNone (default) the Axes’transAxes transform will be used.

title : str or None

The legend’s title. Default is no title (None).

borderpad : float or None

The fractional whitespace inside the legend border.Measured in font-size units.Default isNone which will take the value from thelegend.borderpadrcParam.

labelspacing : float or None

The vertical space between the legend entries.Measured in font-size units.Default isNone which will take the value from thelegend.labelspacingrcParam.

handlelength : float or None

The length of the legend handles.Measured in font-size units.Default isNone which will take the value from thelegend.handlelengthrcParam.

handletextpad : float or None

The pad between the legend handle and text.Measured in font-size units.Default isNone which will take the value from thelegend.handletextpadrcParam.

borderaxespad : float or None

The pad between the axes and legend border.Measured in font-size units.Default isNone which will take the value from thelegend.borderaxespadrcParam.

columnspacing : float or None

The spacing between columns.Measured in font-size units.Default isNone which will take the value from thelegend.columnspacingrcParam.

handler_map : dict or None

The custom dictionary mapping instances or types to a legendhandler. Thishandler_map updates the default handler mapfound atmatplotlib.legend.Legend.get_legend_handler_map().

Notes

Not all kinds of artist are supported by the legend command.SeeLegend guide for details.

Examples

(Source code,png,pdf)

../_images/legend_demo7.png
matplotlib.pyplot.locator_params(axis='both',tight=None,**kwargs)

Control behavior of tick locators.

Keyword arguments:

axis
[‘x’ | ‘y’ | ‘both’] Axis on which to operate;default is ‘both’.
tight
[True | False | None] Parameter passed toautoscale_view().Default is None, for no change.

Remaining keyword arguments are passed to directly to theset_params() method.

Typically one might want to reduce the maximum numberof ticks and use tight bounds when plotting smallsubplots, for example:

ax.locator_params(tight=True,nbins=4)

Because the locator is involved in autoscaling,autoscale_view() is called automatically afterthe parameters are changed.

This presently works only for theMaxNLocator usedby default on linear axes, but it may be generalized.

matplotlib.pyplot.loglog(*args,**kwargs)

Make a plot with log scaling on both thex andy axis.

loglog() supports all the keywordarguments ofplot() andmatplotlib.axes.Axes.set_xscale() /matplotlib.axes.Axes.set_yscale().

Notable keyword arguments:

basex/basey: scalar > 1
Base of thex/y logarithm
subsx/subsy: [None | sequence ]
The location of the minorx/y ticks;None defaultsto autosubs, which depend on the number of decades in theplot; seematplotlib.axes.Axes.set_xscale() /matplotlib.axes.Axes.set_yscale() for details
nonposx/nonposy: [‘mask’ | ‘clip’ ]
Non-positive values inx ory can be masked asinvalid, or clipped to a very small positive number

The remaining valid kwargs areLine2D properties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number

Example:

(Source code,png,pdf)

../_images/log_demo3.png
matplotlib.pyplot.magma()

set the default colormap to magma and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.magnitude_spectrum(x,Fs=None,Fc=None,window=None,pad_to=None,sides=None,scale=None,hold=None,data=None,**kwargs)

Plot the magnitude spectrum.

Call signature:

magnitude_spectrum(x,Fs=2,Fc=0,window=mlab.window_hanning,pad_to=None,sides='default',**kwargs)

Compute the magnitude spectrum ofx. Data is padded to alength ofpad_to and the windowing functionwindow is applied tothe signal.

Parameters:

x : 1-D array or sequence

Array or sequence containing the data

Fs : scalar

The sampling frequency (samples per time unit). It is usedto calculate the Fourier frequencies, freqs, in cycles per timeunit. The default value is 2.

window : callable or ndarray

A function or a vector of lengthNFFT. To create windowvectors seewindow_hanning(),window_none(),numpy.blackman(),numpy.hamming(),numpy.bartlett(),scipy.signal(),scipy.signal.get_window(), etc. The default iswindow_hanning(). If a function is passed as theargument, it must take a data segment as an argument andreturn the windowed version of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ]

Specifies which sides of the spectrum to return. Default gives thedefault behavior, which returns one-sided for real data and bothfor complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad_to : integer

The number of points to which the data segment is padded whenperforming the FFT. While not increasing the actual resolution ofthe spectrum (the minimum distance between resolvable peaks),this can give more points in the plot, allowing for moredetail. This corresponds to then parameter in the call to fft().The default is None, which setspad_to equal to the length of theinput signal (i.e. no padding).

scale : [ ‘default’ | ‘linear’ | ‘dB’ ]

The scaling of the values in thespec. ‘linear’ is no scaling.‘dB’ returns the values in dB scale. Whenmode is ‘density’,this is dB power (10 * log10). Otherwise this is dB amplitude(20 * log10). ‘default’ is ‘linear’.

Fc : integer

The center frequency ofx (defaults to 0), which offsetsthe x extents of the plot to reflect the frequency range usedwhen a signal is acquired and then filtered and downsampled tobaseband.

**kwargs :

Keyword arguments control theLine2Dproperties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
Returns:

spectrum : 1-D array

The values for the magnitude spectrum before scaling (real valued)

freqs : 1-D array

The frequencies corresponding to the elements inspectrum

line : aLine2D instance

The line created by this function

See also

psd()
psd() plots the power spectral density.`.
angle_spectrum()
angle_spectrum() plots the angles of the corresponding frequencies.
phase_spectrum()
phase_spectrum() plots the phase (unwrapped angle) of the corresponding frequencies.
specgram()
specgram() can plot the magnitude spectrum of segments within the signal in a colormap.
In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, the following arguments are replaced bydata[<arg>]: * All arguments with the following names: ‘x’.

Examples

(Source code,png,pdf)

../_images/spectrum_demo2.png
matplotlib.pyplot.margins(*args,**kw)

Set or retrieve autoscaling margins.

signatures:

margins()

returns xmargin, ymargin

margins(margin)margins(xmargin,ymargin)margins(x=xmargin,y=ymargin)margins(...,tight=False)

All three forms above set the xmargin and ymargin parameters.All keyword parameters are optional. A single argumentspecifies both xmargin and ymargin. Thetight parameteris passed toautoscale_view(), which is executed aftera margin is changed; the default here isTrue, on theassumption that when margins are specified, no additionalpadding to match tick marks is usually desired. Settingtight toNone will preserve the previous setting.

Specifying any margin changes only the autoscaling; for example,ifxmargin is not None, thenxmargin times the X datainterval will be added to each end of that interval beforeit is used in autoscaling.

matplotlib.pyplot.matshow(A,fignum=None,**kw)

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

The origin is set at the upper left hand corner and rows (firstdimension of the array) are displayed horizontally. The aspectratio of the figure window is that of the array, unless this wouldmake an excessively short or narrow figure.

Tick labels for the xaxis are placed on top.

With the exception offignum, keyword arguments are passed toimshow(). You may set theoriginkwarg to “lower” if you want the first row in the array to beat the bottom instead of the top.

fignum: [ None | integer | False ]

By default,matshow() creates a new figure window withautomatic numbering. Iffignum is given as an integer, thecreated figure will use this figure number. Because of howmatshow() tries to set the figure aspect ratio to be theone of the array, if you provide the number of an alreadyexisting figure, strange things may happen.

Iffignum isFalse or 0, a new figure window willNOT be created.

matplotlib.pyplot.minorticks_off()

Remove minor ticks from the current plot.

matplotlib.pyplot.minorticks_on()

Display minor ticks on the current plot.

Displaying minor ticks reduces performance; turn them off usingminorticks_off() if drawing speed is a problem.

matplotlib.pyplot.nipy_spectral()

set the default colormap to nipy_spectral and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.over(func,*args,**kwargs)

Deprecated since version 2.0:pyplot.hold is deprecated.Future behavior will be consistent with the long-time default:plot commands add elements without first clearing theAxes and/or Figure.

Call a function with hold(True).

Calls:

func(*args,**kwargs)

withhold(True) and then restores the hold state.

matplotlib.pyplot.pause(interval)

Pause forinterval seconds.

If there is an active figure it will be updated and displayed,and the GUI event loop will run during the pause.

If there is no active figure, or if a non-interactive backendis in use, this executes time.sleep(interval).

This can be used for crude animation. For more complexanimation, seematplotlib.animation.

This function is experimental; its behavior may be changedor extended in a future release.

matplotlib.pyplot.pcolor(*args,**kwargs)

Create a pseudocolor plot of a 2-D array.

Note

pcolor can be very slow for large arrays; considerusing the similar but much fasterpcolormesh() instead.

Call signatures:

pcolor(C,**kwargs)pcolor(X,Y,C,**kwargs)

C is the array of color values.

X andY, if given, specify the (x,y) coordinates ofthe colored quadrilaterals; the quadrilateral for C[i,j] hascorners at:

(X[i,j],Y[i,j]),(X[i,j+1],Y[i,j+1]),(X[i+1,j],Y[i+1,j]),(X[i+1,j+1],Y[i+1,j+1]).

Ideally the dimensions ofX andY should be one greaterthan those ofC; if the dimensions are the same, then thelast row and column ofC will be ignored.

Note that the column index corresponds to thex-coordinate, and the row index corresponds toy; fordetails, see theGrid Orientation section below.

If either or both ofX andY are 1-D arrays or column vectors,they will be expanded as needed into the appropriate 2-D arrays,making a rectangular grid.

X,Y andC may be masked arrays. If either C[i, j], or oneof the vertices surrounding C[i,j] (X orY at [i, j], [i+1, j],[i, j+1],[i+1, j+1]) is masked, nothing is plotted.

Keyword arguments:

cmap: [None | Colormap ]
Amatplotlib.colors.Colormap instance. IfNone, userc settings.
norm: [None | Normalize ]
Anmatplotlib.colors.Normalize instance is usedto scale luminance data to 0,1. IfNone, defaults tonormalize().
vmin/vmax: [None | scalar ]
vmin andvmax are used in conjunction withnorm tonormalize luminance data. If either isNone, itis autoscaled to the respective min or maxof the color arrayC. If notNone,vmin orvmax passed in here override any pre-existing valuessupplied in thenorm instance.
shading: [ ‘flat’ | ‘faceted’ ]

If ‘faceted’, a black grid is drawn around each rectangle; if‘flat’, edges are not drawn. Default is ‘flat’, contrary toMATLAB.

This kwarg is deprecated; please use ‘edgecolors’ instead:
  • shading=’flat’ – edgecolors=’none’
  • shading=’faceted – edgecolors=’k’
edgecolors: [None |'none' | color | color sequence]

IfNone, the rc setting is used by default.

If'none', edges will not be visible.

An mpl color or sequence of colors will set the edge color

alpha:0<=scalar<=1 orNone
the alpha blending value
snap: bool
Whether to snap the mesh to pixel boundaries.

Return value is amatplotlib.collections.Collectioninstance.

The grid orientation follows the MATLAB convention: anarrayC with shape (nrows,ncolumns) is plotted withthe column number asX and the row number asY, increasingup; hence it is plotted the way the array would be printed,except that theY axis is reversed. That is,C is takenasC*(*y,x).

Similarly formeshgrid():

x=np.arange(5)y=np.arange(3)X,Y=np.meshgrid(x,y)

is equivalent to:

X=array([[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]])Y=array([[0,0,0,0,0],[1,1,1,1,1],[2,2,2,2,2]])

so if you have:

C=rand(len(x),len(y))

then you need to transpose C:

pcolor(X,Y,C.T)

or:

pcolor(C.T)

MATLABpcolor() always discards the last row and columnofC, but matplotlib displays the last row and column ifX andY are not specified, or ifX andY have one more row andcolumn thanC.

kwargs can be used to control thePolyCollection properties:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
visible[True | False]
zorderany number

Note

The defaultantialiaseds is False if the defaultedgecolors*=”none” is used. This eliminates artificial linesat patch boundaries, and works regardless of the value ofalpha. If *edgecolors is not “none”, then the defaultantialiaseds is taken fromrcParams[‘patch.antialiased’], which defaults toTrue.Stroking the edges may be preferred ifalpha is 1, butwill cause artifacts otherwise.

See also

pcolormesh()
For an explanation of the differences betweenpcolor and pcolormesh.

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All positional and all keyword arguments.
matplotlib.pyplot.pcolormesh(*args,**kwargs)

Plot a quadrilateral mesh.

Call signatures:

pcolormesh(C)pcolormesh(X,Y,C)pcolormesh(C,**kwargs)

Create a pseudocolor plot of a 2-D array.

pcolormesh is similar topcolor(),but uses a different mechanism and returns a differentobject; pcolor returns aPolyCollection but pcolormeshreturns aQuadMesh. It is much faster,so it is almost always preferred for large arrays.

C may be a masked array, butX andY may not. Maskedarray support is implemented viacmap andnorm; incontrast,pcolor() simply does notdraw quadrilaterals with masked colors or vertices.

Keyword arguments:

cmap: [None | Colormap ]
Amatplotlib.colors.Colormap instance. IfNone, userc settings.
norm: [None | Normalize ]
Amatplotlib.colors.Normalize instance is used toscale luminance data to 0,1. IfNone, defaults tonormalize().
vmin/vmax: [None | scalar ]
vmin andvmax are used in conjunction withnorm tonormalize luminance data. If either isNone, itis autoscaled to the respective min or maxof the color arrayC. If notNone,vmin orvmax passed in here override any pre-existing valuessupplied in thenorm instance.
shading: [ ‘flat’ | ‘gouraud’ ]
‘flat’ indicates a solid color for each quad. When‘gouraud’, each quad will be Gouraud shaded. When gouraudshading, edgecolors is ignored.
edgecolors: [None |'None' |'face' | color |
color sequence]

IfNone, the rc setting is used by default.

If'None', edges will not be visible.

If'face', edges will have the same color as the faces.

An mpl color or sequence of colors will set the edge color

alpha:0<=scalar<=1 orNone
the alpha blending value

Return value is amatplotlib.collections.QuadMeshobject.

kwargs can be used to control thematplotlib.collections.QuadMesh properties:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
visible[True | False]
zorderany number

See also

pcolor()
For an explanation of the grid orientation(Grid Orientation)and the expansion of 1-DX and/orY to 2-D arrays.

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All positional and all keyword arguments.
matplotlib.pyplot.phase_spectrum(x,Fs=None,Fc=None,window=None,pad_to=None,sides=None,hold=None,data=None,**kwargs)

Plot the phase spectrum.

Call signature:

phase_spectrum(x,Fs=2,Fc=0,window=mlab.window_hanning,pad_to=None,sides='default',**kwargs)

Compute the phase spectrum (unwrapped angle spectrum) ofx.Data is padded to a length ofpad_to and the windowing functionwindow is applied to the signal.

Parameters:

x : 1-D array or sequence

Array or sequence containing the data

Fs : scalar

The sampling frequency (samples per time unit). It is usedto calculate the Fourier frequencies, freqs, in cycles per timeunit. The default value is 2.

window : callable or ndarray

A function or a vector of lengthNFFT. To create windowvectors seewindow_hanning(),window_none(),numpy.blackman(),numpy.hamming(),numpy.bartlett(),scipy.signal(),scipy.signal.get_window(), etc. The default iswindow_hanning(). If a function is passed as theargument, it must take a data segment as an argument andreturn the windowed version of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ]

Specifies which sides of the spectrum to return. Default gives thedefault behavior, which returns one-sided for real data and bothfor complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad_to : integer

The number of points to which the data segment is padded whenperforming the FFT. While not increasing the actual resolution ofthe spectrum (the minimum distance between resolvable peaks),this can give more points in the plot, allowing for moredetail. This corresponds to then parameter in the call to fft().The default is None, which setspad_to equal to the length of theinput signal (i.e. no padding).

Fc : integer

The center frequency ofx (defaults to 0), which offsetsthe x extents of the plot to reflect the frequency range usedwhen a signal is acquired and then filtered and downsampled tobaseband.

**kwargs :

Keyword arguments control theLine2Dproperties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
Returns:

spectrum : 1-D array

The values for the phase spectrum in radians (real valued)

freqs : 1-D array

The frequencies corresponding to the elements inspectrum

line : aLine2D instance

The line created by this function

See also

magnitude_spectrum()
magnitude_spectrum() plots the magnitudes of the corresponding frequencies.
angle_spectrum()
angle_spectrum() plots the wrapped version of this function.
specgram()
specgram() can plot the phase spectrum of segments within the signal in a colormap.
In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, the following arguments are replaced bydata[<arg>]: * All arguments with the following names: ‘x’.

Examples

(Source code,png,pdf)

../_images/spectrum_demo2.png
matplotlib.pyplot.pie(x,explode=None,labels=None,colors=None,autopct=None,pctdistance=0.6,shadow=False,labeldistance=1.1,startangle=None,radius=None,counterclock=True,wedgeprops=None,textprops=None,center=(0,0),frame=False,hold=None,data=None)

Plot a pie chart.

Make a pie chart of arrayx. The fractional area of eachwedge is given byx/sum(x). Ifsum(x)<=1, then thevalues of x give the fractional area directly and the arraywill not be normalized. The wedges are plottedcounterclockwise, by default starting from the x-axis.

Parameters:

x : array-like

The input array used to make the pie chart.

explode : array-like, optional, default: None

If notNone, is alen(x) array which specifies thefraction of the radius with which to offset each wedge.

labels : list, optional, default: None

A sequence of strings providing the labels for each wedge

colors : array-like, optional, default: None

A sequence of matplotlib color args through which the pie chartwill cycle. IfNone, will use the colors in the currentlyactive cycle.

autopct : None (default), string, or function, optional

If notNone, is a string or function used to label the wedgeswith their numeric value. The label will be placed inside thewedge. If it is a format string, the label will befmt%pct.If it is a function, it will be called.

pctdistance : float, optional, default: 0.6

The ratio between the center of each pie slice and thestart of the text generated byautopct. Ignored ifautopct isNone.

shadow : bool, optional, default: False

Draw a shadow beneath the pie.

labeldistance : float, optional, default: 1.1

The radial distance at which the pie labels are drawn

startangle : float, optional, default: None

If notNone, rotates the start of the pie chart byangledegrees counterclockwise from the x-axis.

radius : float, optional, default: None

The radius of the pie, ifradius isNone it will be set to 1.

counterclock : bool, optional, default: True

Specify fractions direction, clockwise or counterclockwise.

wedgeprops : dict, optional, default: None

Dict of arguments passed to the wedge objects making the pie.For example, you can pass in``wedgeprops = {‘linewidth’: 3}``to set the width of the wedge border lines equal to 3.For more details, look at the doc/arguments of the wedge object.By defaultclip_on=False.

textprops : dict, optional, default: None

Dict of arguments to pass to the text objects.

center : list of float, optional, default: (0, 0)

Center position of the chart. Takes value (0, 0) or is asequence of 2 scalars.

frame : bool, optional, default: False

Plot axes frame with the chart if true.

Returns:

patches : list

A sequence ofmatplotlib.patches.Wedge instances

texts : list

A is a list of the labelmatplotlib.text.Text instances.

autotexts : list

A is a list ofText instances for thenumeric labels. Is returned only if parameterautopct isnotNone.

Notes

The pie chart will probably look best if the figure and axes aresquare, or the Axes aspect is equal.

Examples

(Source code,png,pdf)

../_images/pie_demo_features3.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘colors’, ‘explode’, ‘labels’, ‘x’.
matplotlib.pyplot.pink()

set the default colormap to pink and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.plasma()

set the default colormap to plasma and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.plot(*args,**kwargs)

Plot lines and/or markers to theAxes.args is a variable lengthargument, allowing for multiplex,y pairs with anoptional format string. For example, each of the following islegal:

plot(x,y)# plot x and y using default line style and colorplot(x,y,'bo')# plot x and y using blue circle markersplot(y)# plot y using x as index array 0..N-1plot(y,'r+')# ditto, but with red plusses

Ifx and/ory is 2-dimensional, then the corresponding columnswill be plotted.

If used with labeled data, make sure that the color spec is notincluded as an element in data, as otherwise the last caseplot("v","r",data={"v":...,"r":...)can be interpreted as the first case which would doplot(v,r)using the default line style and color.

If not used with labeled data (i.e., without a data argument),an arbitrary number ofx,y,fmt groups can be specified, as in:

a.plot(x1,y1,'g^',x2,y2,'g-')

Return value is a list of lines that were added.

By default, each line is assigned a different style specified by a‘style cycle’. To change this behavior, you can edit theaxes.prop_cycle rcParam.

The following format string characters are accepted to controlthe line style or marker:

characterdescription
'-'solid line style
'--'dashed line style
'-.'dash-dot line style
':'dotted line style
'.'point marker
','pixel marker
'o'circle marker
'v'triangle_down marker
'^'triangle_up marker
'<'triangle_left marker
'>'triangle_right marker
'1'tri_down marker
'2'tri_up marker
'3'tri_left marker
'4'tri_right marker
's'square marker
'p'pentagon marker
'*'star marker
'h'hexagon1 marker
'H'hexagon2 marker
'+'plus marker
'x'x marker
'D'diamond marker
'd'thin_diamond marker
'|'vline marker
'_'hline marker

The following color abbreviations are supported:

charactercolor
‘b’blue
‘g’green
‘r’red
‘c’cyan
‘m’magenta
‘y’yellow
‘k’black
‘w’white

In addition, you can specify colors in many weird andwonderful ways, including full names ('green'), hexstrings ('#008000'), RGB or RGBA tuples ((0,1,0,1)) orgrayscale intensities as a string ('0.8'). Of these, thestring specifications can be used in place of afmt group,but the tuple forms can be used only askwargs.

Line styles and colors are combined in a single format string, as in'bo' for blue circles.

Thekwargs can be used to set line properties (any property that hasaset_* method). You can use this to set a line label (for autolegends), linewidth, anitialising, marker face color, etc. Here is anexample:

plot([1,2,3],[1,2,3],'go-',label='line 1',linewidth=2)plot([1,2,3],[1,4,9],'rs',label='line 2')axis([0,4,0,10])legend()

If you make multiple lines with one plot command, the kwargsapply to all those lines, e.g.:

plot(x1,y1,x2,y2,antialiased=False)

Neither line will be antialiased.

You do not need to use format strings, which are justabbreviations. All of the line properties can be controlledby keyword arguments. For example, you can set the color,marker, linestyle, and markercolor with:

plot(x,y,color='green',linestyle='dashed',marker='o',markerfacecolor='blue',markersize=12).

SeeLine2D for details.

The kwargs areLine2D properties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number

kwargsscalex andscaley, if defined, are passed on toautoscale_view() to determinewhether thex andy axes are autoscaled; the default isTrue.

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’, ‘y’.
matplotlib.pyplot.plot_date(x,y,fmt='o',tz=None,xdate=True,ydate=False,hold=None,data=None,**kwargs)

A plot with data that contains dates.

Similar to theplot() command, exceptthex ory (or both) data is considered to be dates, and theaxis is labeled accordingly.

x and/ory can be a sequence of dates represented as floatdays since 0001-01-01 UTC.

Note if you are using custom date tickers and formatters, itmay be necessary to set the formatters/locators after the callto meth:plot_date since meth:plot_date will set thedefault tick locator toclass:matplotlib.dates.AutoDateLocator (if the ticklocator is not already set to aclass:matplotlib.dates.DateLocator instance) and thedefault tick formatter toclass:matplotlib.dates.AutoDateFormatter (if the tickformatter is not already set to aclass:matplotlib.dates.DateFormatter instance).

Parameters:

fmt : string

The plot format string.

tz : [None | timezone string |tzinfo instance]

The time zone to use in labeling dates. IfNone, defaults to rcvalue.

xdate : boolean

IfTrue, thex-axis will be labeled with dates.

ydate : boolean

IfTrue, they-axis will be labeled with dates.

Returns:

lines

Other Parameters:
 

kwargs :matplotlib.lines.Line2D

properties :

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number

.. note::

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’, ‘y’.

See also

matplotlib.dates
helper functions on dates
matplotlib.dates.date2num
how to convert dates to num
matplotlib.dates.num2date
how to convert num to dates
matplotlib.dates.drange
how floating point dates
matplotlib.pyplot.plotfile(fname,cols=(0,),plotfuncs=None,comments='#',skiprows=0,checkrows=5,delimiter=',',names=None,subplots=True,newfig=True,**kwargs)

Plot the data in in a file.

cols is a sequence of column identifiers to plot. An identifieris either an int or a string. If it is an int, it indicates thecolumn number. If it is a string, it indicates the column header.matplotlib will make column headers lower case, replace spaces withunderscores, and remove all illegal characters; so'AdjClose*'will have name'adj_close'.

  • If len(cols) == 1, only that column will be plotted on they axis.
  • If len(cols) > 1, the first element will be an identifier fordata for thex axis and the remaining elements will be thecolumn indexes for multiple subplots ifsubplots isTrue(the default), or for lines in a single subplot ifsubplotsisFalse.

plotfuncs, if notNone, is a dictionary mapping identifier toanAxes plotting function as a string.Default is ‘plot’, other choices are ‘semilogy’, ‘fill’, ‘bar’,etc. You must use the same type of identifier in thecolsvector as you use in theplotfuncs dictionary, e.g., integercolumn numbers in both or column names in both. IfsubplotsisFalse, then including any function such as ‘semilogy’that changes the axis scaling will set the scaling for allcolumns.

comments,skiprows,checkrows,delimiter, andnamesare all passed on tomatplotlib.pylab.csv2rec() toload the data into a record array.

Ifnewfig isTrue, the plot always will be made in a new figure;ifFalse, it will be made in the current figure if one exists,else in a new figure.

kwargs are passed on to plotting functions.

Example usage:

# plot the 2nd and 4th column against the 1st in two subplotsplotfile(fname,(0,1,3))# plot using column names; specify an alternate plot type for volumeplotfile(fname,('date','volume','adj_close'),plotfuncs={'volume':'semilogy'})

Note: plotfile is intended as a convenience for quickly plottingdata from flat files; it is not intended as an alternativeinterface to general plotting with pyplot or matplotlib.

matplotlib.pyplot.polar(*args,**kwargs)

Make a polar plot.

call signature:

polar(theta,r,**kwargs)

Multipletheta,r arguments are supported, with formatstrings, as inplot().

matplotlib.pyplot.prism()

set the default colormap to prism and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.psd(x,NFFT=None,Fs=None,Fc=None,detrend=None,window=None,noverlap=None,pad_to=None,sides=None,scale_by_freq=None,return_line=None,hold=None,data=None,**kwargs)

Plot the power spectral density.

Call signature:

psd(x,NFFT=256,Fs=2,Fc=0,detrend=mlab.detrend_none,window=mlab.window_hanning,noverlap=0,pad_to=None,sides='default',scale_by_freq=None,return_line=None,**kwargs)

The power spectral density by Welch’s averageperiodogram method. The vectorx is divided intoNFFT lengthsegments. Each segment is detrended by functiondetrend andwindowed by functionwindow.noverlap gives the length ofthe overlap between segments. Theof each segment are averaged to compute,with a scaling to correct for power loss due to windowing.

If len(x) <NFFT, it will be zero padded toNFFT.

Parameters:

x : 1-D array or sequence

Array or sequence containing the data

Fs : scalar

The sampling frequency (samples per time unit). It is usedto calculate the Fourier frequencies, freqs, in cycles per timeunit. The default value is 2.

window : callable or ndarray

A function or a vector of lengthNFFT. To create windowvectors seewindow_hanning(),window_none(),numpy.blackman(),numpy.hamming(),numpy.bartlett(),scipy.signal(),scipy.signal.get_window(), etc. The default iswindow_hanning(). If a function is passed as theargument, it must take a data segment as an argument andreturn the windowed version of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ]

Specifies which sides of the spectrum to return. Default gives thedefault behavior, which returns one-sided for real data and bothfor complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad_to : integer

The number of points to which the data segment is padded whenperforming the FFT. This can be different fromNFFT, whichspecifies the number of data points used. While not increasingthe actual resolution of the spectrum (the minimum distance betweenresolvable peaks), this can give more points in the plot,allowing for more detail. This corresponds to then parameterin the call to fft(). The default is None, which setspad_toequal toNFFT

NFFT : integer

The number of data points used in each block for the FFT.A power 2 is most efficient. The default value is 256.This shouldNOT be used to get zero padding, or the scaling of theresult will be incorrect. Usepad_to for this instead.

detrend : {‘default’, ‘constant’, ‘mean’, ‘linear’, ‘none’} or callable

The function applied to each segment before fft-ing,designed to remove the mean or linear trend. Unlike inMATLAB, where thedetrend parameter is a vector, inmatplotlib is it a function. Thepylabmodule definesdetrend_none(),detrend_mean(), anddetrend_linear(), but you can usea custom function as well. You can also use a string to chooseone of the functions. ‘default’, ‘constant’, and ‘mean’ calldetrend_mean(). ‘linear’ callsdetrend_linear(). ‘none’ callsdetrend_none().

scale_by_freq : boolean, optional

Specifies whether the resulting density values should be scaledby the scaling frequency, which gives density in units of Hz^-1.This allows for integration over the returned frequency values.The default is True for MATLAB compatibility.

noverlap : integer

The number of points of overlap between segments.The default value is 0 (no overlap).

Fc : integer

The center frequency ofx (defaults to 0), which offsetsthe x extents of the plot to reflect the frequency range usedwhen a signal is acquired and then filtered and downsampled tobaseband.

return_line : bool

Whether to include the line object plotted in the returned values.Default is False.

**kwargs :

Keyword arguments control theLine2Dproperties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number
Returns:

Pxx : 1-D array

The values for the power spectrumP_{xx} before scaling(real valued)

freqs : 1-D array

The frequencies corresponding to the elements inPxx

line : aLine2D instance

The line created by this function.Only returned ifreturn_line is True.

See also

specgram()
specgram() differs in the default overlap; in not returning the mean of the segment periodograms; in returning the times of the segments; and in plotting a colormap instead of a line.
magnitude_spectrum()
magnitude_spectrum() plots the magnitude spectrum.
csd()
csd() plots the spectral density between two signals.
In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, the following arguments are replaced bydata[<arg>]: * All arguments with the following names: ‘x’.

Notes

For plotting, the power is plotted as for decibels, thoughPxx itselfis returned.

References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures,John Wiley & Sons (1986)

Examples

(Source code,png,pdf)

../_images/psd_demo_00_002.png
matplotlib.pyplot.quiver(*args,**kw)

Plot a 2-D field of arrows.

Call signatures:

quiver(U,V,**kw)quiver(U,V,C,**kw)quiver(X,Y,U,V,**kw)quiver(X,Y,U,V,C,**kw)

U andV are the arrow data,X andY set the locaiton of thearrows, andC sets the color of the arrows. These arguments may be 1-D or2-D arrays or sequences.

IfX andY are absent, they will be generated as a uniform grid.IfU andV are 2-D arrays andX andY are 1-D, and iflen(X) andlen(Y) match the column and row dimensions ofU, thenX andY will beexpanded withnumpy.meshgrid().

The default settings auto-scales the length of the arrows to a reasonable size.To change this behavior see thescale andscale_units kwargs.

The defaults give a slightly swept-back arrow; to make the head atriangle, makeheadaxislength the same asheadlength. To make thearrow more pointed, reduceheadwidth or increaseheadlength andheadaxislength. To make the head smaller relative to the shaft,scale down all the head parameters. You will probably do best to leaveminshaft alone.

linewidths andedgecolors can be used to customize the arrowoutlines.

Parameters:

X : 1D or 2D array, sequence, optional

The x coordinates of the arrow locations

Y : 1D or 2D array, sequence, optional

The y coordinates of the arrow locations

U : 1D or 2D array or masked array, sequence

The x components of the arrow vectors

V : 1D or 2D array or masked array, sequence

The y components of the arrow vectors

C : 1D or 2D array, sequence, optional

The arrow colors

units : [ ‘width’ | ‘height’ | ‘dots’ | ‘inches’ | ‘x’ | ‘y’ | ‘xy’ ]

The arrow dimensions (except forlength) are measured in multiples ofthis unit.

‘width’ or ‘height’: the width or height of the axis

‘dots’ or ‘inches’: pixels or inches, based on the figure dpi

‘x’, ‘y’, or ‘xy’: respectivelyX,Y, orin data units

The arrows scale differently depending on the units. For‘x’ or ‘y’, the arrows get larger as one zooms in; for otherunits, the arrow size is independent of the zoom state. For‘width or ‘height’, the arrow size increases with the width andheight of the axes, respectively, when the window is resized;for ‘dots’ or ‘inches’, resizing does not change the arrows.

angles : [ ‘uv’ | ‘xy’ ], array, optional

Method for determining the angle of the arrows. Default is ‘uv’.

‘uv’: the arrow axis aspect ratio is 1 so thatifU*==*V the orientation of the arrow on the plot is 45 degreescounter-clockwise from the horizontal axis (positive to the right).

‘xy’: arrows point from (x,y) to (x+u, y+v).Use this for plotting a gradient field, for example.

Alternatively, arbitrary angles may be specified as an arrayof values in degrees, counter-clockwise from the horizontal axis.

Note: inverting a data axis will correspondingly invert thearrows only withangles='xy'.

scale : None, float, optional

Number of data units per arrow length unit, e.g., m/s per plot width; asmaller scale parameter makes the arrow longer. Default isNone.

IfNone, a simple autoscaling algorithm is used, based on the averagevector length and the number of vectors. The arrow length unit is given bythescale_units parameter

scale_units : [ ‘width’ | ‘height’ | ‘dots’ | ‘inches’ | ‘x’ | ‘y’ | ‘xy’ ], None, optional

If thescale kwarg isNone, the arrow length unit. Default isNone.

e.g.scale_units is ‘inches’,scale is 2.0, and(u,v)=(1,0), then the vector will be 0.5 inches long.

Ifscale_units is ‘width’/’height’, then the vector will be half thewidth/height of the axes.

Ifscale_units is ‘x’ then the vector will be 0.5 x-axisunits. To plot vectors in the x-y plane, with u and v havingthe same units as x and y, useangles='xy',scale_units='xy',scale=1.

width : scalar, optional

Shaft width in arrow units; default depends on choice of units,above, and number of vectors; a typical starting value is about0.005 times the width of the plot.

headwidth : scalar, optional

Head width as multiple of shaft width, default is 3

headlength : scalar, optional

Head length as multiple of shaft width, default is 5

headaxislength : scalar, optional

Head length at shaft intersection, default is 4.5

minshaft : scalar, optional

Length below which arrow scales, in units of head length. Do notset this to less than 1, or small arrows will look terrible!Default is 1

minlength : scalar, optional

Minimum length as a multiple of shaft width; if an arrow lengthis less than this, plot a dot (hexagon) of this diameter instead.Default is 1.

pivot : [ ‘tail’ | ‘mid’ | ‘middle’ | ‘tip’ ], optional

The part of the arrow that is at the grid point; the arrow rotatesabout this point, hence the namepivot.

color : [ color | color sequence ], optional

This is a synonym for thePolyCollection facecolor kwarg.IfC has been set,color has no effect.

See also

quiverkey
Add a key to a quiver plot

Notes

AdditionalPolyCollectionkeyword arguments:

PropertyDescription
agg_filterunknown
alphafloat or None
animated[True | False]
antialiased or antialiasedsBoolean or sequence of booleans
arrayunknown
axesanAxes instance
clima length 2 sequence of floats
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
cmapa colormap or registered colormap name
colormatplotlib color arg or sequence of rgba tuples
containsa callable function
edgecolor or edgecolorsmatplotlib color spec or sequence of specs
facecolor or facecolorsmatplotlib color spec or sequence of specs
figureamatplotlib.figure.Figure instance
gidan id string
hatch[ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ]
labelstring or anything printable with ‘%s’ conversion.
linestyle or dashes or linestyles[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or linewidths or lwfloat or sequence of floats
normunknown
offset_positionunknown
offsetsfloat or sequence of floats
path_effectsunknown
picker[None|float|boolean|callable]
pickradiusunknown
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
urlsunknown
visible[True | False]
zorderany number

Examples

(Source code,png,pdf)

../_images/quiver_simple_demo2.png
matplotlib.pyplot.quiverkey(*args,**kw)

Add a key to a quiver plot.

Call signature:

quiverkey(Q,X,Y,U,label,**kw)

Arguments:

Q:
The Quiver instance returned by a call to quiver.
X,Y:
The location of the key; additional explanation follows.
U:
The length of the key
label:
A string with the length and units of the key

Keyword arguments:

coordinates = [ ‘axes’ | ‘figure’ | ‘data’ | ‘inches’ ]
Coordinate system and units forX,Y: ‘axes’ and ‘figure’ arenormalized coordinate systems with 0,0 in the lower left and 1,1in the upper right; ‘data’ are the axes data coordinates (used forthe locations of the vectors in the quiver plot itself); ‘inches’is position in the figure in inches, with 0,0 at the lower leftcorner.
color:
overrides face and edge colors fromQ.
labelpos = [ ‘N’ | ‘S’ | ‘E’ | ‘W’ ]
Position the label above, below, to the right, to the left of thearrow, respectively.
labelsep:
Distance in inches between the arrow and the label. Default is0.1
labelcolor:
defaults to defaultText color.
fontproperties:
A dictionary with keyword arguments accepted by theFontProperties initializer:family,style,variant,size,weight

Any additional keyword arguments are used to override vectorproperties taken fromQ.

The positioning of the key depends onX,Y,coordinates, andlabelpos. Iflabelpos is ‘N’ or ‘S’,X,Y give the positionof the middle of the key arrow. Iflabelpos is ‘E’,X,Ypositions the head, and iflabelpos is ‘W’,X,Y positions thetail; in either of these two cases,X,Y is somewhere in themiddle of the arrow+label key object.

matplotlib.pyplot.rc(*args,**kwargs)

Set the current rc params. Group is the grouping for the rc, e.g.,forlines.linewidth the group islines, foraxes.facecolor, the group isaxes, and so on. Group mayalso be a list or tuple of group names, e.g., (xtick,ytick).kwargs is a dictionary attribute name/value pairs, e.g.,:

rc('lines',linewidth=2,color='r')

sets the current rc params and is equivalent to:

rcParams['lines.linewidth']=2rcParams['lines.color']='r'

The following aliases are available to save typing for interactiveusers:

AliasProperty
‘lw’‘linewidth’
‘ls’‘linestyle’
‘c’‘color’
‘fc’‘facecolor’
‘ec’‘edgecolor’
‘mew’‘markeredgewidth’
‘aa’‘antialiased’

Thus you could abbreviate the above rc command as:

rc('lines',lw=2,c='r')

Note you can use python’s kwargs dictionary facility to storedictionaries of default parameters. e.g., you can customize thefont rc as follows:

font={'family':'monospace','weight':'bold','size':'larger'}rc('font',**font)# pass in the font dict as kwargs

This enables you to easily switch between several configurations. Usematplotlib.style.use('default') orrcdefaults() torestore the default rc params after changes.

matplotlib.pyplot.rc_context(rc=None,fname=None)

Return a context manager for managing rc settings.

This allows one to do:

withmpl.rc_context(fname='screen.rc'):plt.plot(x,a)withmpl.rc_context(fname='print.rc'):plt.plot(x,b)plt.plot(x,c)

The ‘a’ vs ‘x’ and ‘c’ vs ‘x’ plots would have settings from‘screen.rc’, while the ‘b’ vs ‘x’ plot would have settings from‘print.rc’.

A dictionary can also be passed to the context manager:

withmpl.rc_context(rc={'text.usetex':True},fname='screen.rc'):plt.plot(x,a)

The ‘rc’ dictionary takes precedence over the settings loaded from‘fname’. Passing a dictionary only is also valid.

matplotlib.pyplot.rcdefaults()

Restore the rc params from Matplotlib’s internal defaults.

See also

rc_file_defaults
Restore the rc params from the rc file originally loaded by Matplotlib.
matplotlib.style.use
Use a specific style file. Callstyle.use('default') to restore the default style.
matplotlib.pyplot.rgrids(*args,**kwargs)

Get or set the radial gridlines on a polar plot.

call signatures:

lines,labels=rgrids()lines,labels=rgrids(radii,labels=None,angle=22.5,**kwargs)

When called with no arguments,rgrid() simply returns thetuple (lines,labels), wherelines is an array of radialgridlines (Line2D instances) andlabels is an array of tick labels(Text instances). When called witharguments, the labels will appear at the specified radialdistances and angles.

labels, if notNone, is a len(radii) list of strings of thelabels to use at each angle.

Iflabels is None, the rformatter will be used

Examples:

# set the locations of the radial gridlines and labelslines,labels=rgrids((0.25,0.5,1.0))# set the locations and labels of the radial gridlines and labelslines,labels=rgrids((0.25,0.5,1.0),('Tom','Dick','Harry')
matplotlib.pyplot.savefig(*args,**kwargs)

Save the current figure.

Call signature:

savefig(fname,dpi=None,facecolor='w',edgecolor='w',orientation='portrait',papertype=None,format=None,transparent=False,bbox_inches=None,pad_inches=0.1,frameon=None)

The output formats available depend on the backend being used.

Arguments:

fname:

A string containing a path to a filename, or a Pythonfile-like object, or possibly some backend-dependent objectsuch asPdfPages.

Ifformat isNone andfname is a string, the outputformat is deduced from the extension of the filename. Ifthe filename has no extension, the value of the rc parametersavefig.format is used.

Iffname is not a string, remember to specifyformat toensure that the correct backend is used.

Keyword arguments:

dpi: [None |scalar>0 | ‘figure’]
The resolution in dots per inch. IfNone it will default tothe valuesavefig.dpi in the matplotlibrc file. If ‘figure’it will set the dpi to be the value of the figure.
facecolor,edgecolor:
the colors of the figure rectangle
orientation: [ ‘landscape’ | ‘portrait’ ]
not supported on all backends; currently only on postscript output
papertype:
One of ‘letter’, ‘legal’, ‘executive’, ‘ledger’, ‘a0’ through‘a10’, ‘b0’ through ‘b10’. Only supported for postscriptoutput.
format:
One of the file extensions supported by the activebackend. Most backends support png, pdf, ps, eps and svg.
transparent:
IfTrue, the axes patches will all be transparent; thefigure patch will also be transparent unless facecolorand/or edgecolor are specified via kwargs.This is useful, for example, for displayinga plot on top of a colored background on a web page. Thetransparency of these patches will be restored to theiroriginal values upon exit of this function.
frameon:
IfTrue, the figure patch will be colored, ifFalse, thefigure background will be transparent. If not provided, thercParam ‘savefig.frameon’ will be used.
bbox_inches:
Bbox in inches. Only the given portion of the figure issaved. If ‘tight’, try to figure out the tight bbox ofthe figure.
pad_inches:
Amount of padding around the figure when bbox_inches is‘tight’.
bbox_extra_artists:
A list of extra artists that will be considered when thetight bbox is calculated.
matplotlib.pyplot.sca(ax)

Set the current Axes instance toax.

The current Figure is updated to the parent ofax.

matplotlib.pyplot.scatter(x,y,s=None,c=None,marker=None,cmap=None,norm=None,vmin=None,vmax=None,alpha=None,linewidths=None,verts=None,edgecolors=None,hold=None,data=None,**kwargs)

Make a scatter plot ofx vsy

Marker size is scaled bys and marker color is mapped toc

Parameters:

x, y : array_like, shape (n, )

Input data

s : scalar or array_like, shape (n, ), optional

size in points^2. Default isrcParams['lines.markersize']**2.

c : color, sequence, or sequence of color, optional, default: ‘b’

c can be a single color format string, or a sequence of colorspecifications of lengthN, or a sequence ofN numbers to bemapped to colors using thecmap andnorm specified via kwargs(see below). Note thatc should not be a single numeric RGB orRGBA sequence because that is indistinguishable from an array ofvalues to be colormapped.c can be a 2-D array in which therows are RGB or RGBA, however, including the case of a singlerow to specify the same color for all points.

marker :MarkerStyle, optional, default: ‘o’

Seemarkers for more information on the differentstyles of markers scatter supports.marker can be eitheran instance of the class or the text shorthand for a particularmarker.

cmap :Colormap, optional, default: None

AColormap instance or registered name.cmap is only used ifc is an array of floats. If None,defaults to rcimage.cmap.

norm :Normalize, optional, default: None

ANormalize instance is used to scaleluminance data to 0, 1.norm is only used ifc is an array offloats. IfNone, use the defaultnormalize().

vmin, vmax : scalar, optional, default: None

vmin andvmax are used in conjunction withnorm to normalizeluminance data. If either areNone, the min and max of thecolor array is used. Note if you pass anorm instance, yoursettings forvmin andvmax will be ignored.

alpha : scalar, optional, default: None

The alpha blending value, between 0 (transparent) and 1 (opaque)

linewidths : scalar or array_like, optional, default: None

If None, defaults to (lines.linewidth,).

verts : sequence of (x, y), optional

Ifmarker is None, these vertices will be used toconstruct the marker. The center of the marker is locatedat (0,0) in normalized units. The overall marker is rescaledbys.

edgecolors : color or sequence of color, optional, default: None

If None, defaults to ‘face’

If ‘face’, the edge color will always be the same asthe face color.

If it is ‘none’, the patch boundary will notbe drawn.

For non-filled markers, theedgecolors kwargis ignored and forced to ‘face’ internally.

Returns:

paths :PathCollection

Other Parameters:
 

kwargs :Collection properties

See also

plot
to plot scatter plots when markers are identical in size and color

Notes

  • Theplot function will be faster for scatterplots where markersdon’t vary in size or color.

  • Any or all ofx,y,s, andc may be masked arrays, in whichcase all masks will be combined and only unmasked points will beplotted.

    Fundamentally, scatter works with 1-D arrays;x,y,s, andcmay be input as 2-D arrays, but within scatter they will beflattened. The exception isc, which will be flattened only if itssize matches the size ofx andy.

Examples

(Source code,png,pdf)

../_images/scatter_demo3.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘c’, ‘color’, ‘edgecolors’, ‘facecolor’, ‘facecolors’, ‘linewidths’, ‘s’, ‘x’, ‘y’.
matplotlib.pyplot.sci(im)

Set the current image. This image will be the target of colormapcommands likejet(),hot() orclim()). The current image is anattribute of the current axes.

matplotlib.pyplot.semilogx(*args,**kwargs)

Make a plot with log scaling on thex axis.

Parameters:

basex : float, optional

Base of thex logarithm. The scalar should be largerthan 1.

subsx : array_like, optional

The location of the minor xticks;None defaults toautosubs, which depend on the number of decades in theplot; seeset_xscale() fordetails.

nonposx : string, optional, {‘mask’, ‘clip’}

Non-positive values inx can be masked asinvalid, or clipped to a very small positive number.

Returns:

plot

Log-scaled plot on thex axis.

Other Parameters:
 

:class:`~matplotlib.lines.Line2D` properties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
antialiased or aa[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ | ‘round’ | ‘projecting’]
dash_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
figureamatplotlib.figure.Figure instance
fillstyle[‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
gidan id string
labelstring or anything printable with ‘%s’ conversion.
linestyle or ls[‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) |'-' |'--' |'-.' |':' |'None' |'' |'']
linewidth or lwfloat value in points
markerAvalidmarkerstyle
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
path_effectsunknown
pickerfloat distance in points or callable pick functionfn(artist,event)
pickradiusfloat distance in points
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transformamatplotlib.transforms.Transform instance
urla url string
visible[True | False]
xdata1D array
ydata1D array
zorderany number

See also

loglog
For example code and figure.

Notes

This function supports all the keyword arguments ofplot() andmatplotlib.axes.Axes.set_xscale().

matplotlib.pyplot.semilogy(*args,**kwargs)

Make a plot with log scaling on they axis.

Parameters:

basey : scalar > 1

Base of they logarithm.

subsy:None or iterable

The location of the minor yticks. None defaults toautosubs, which depend on the number of decades in theplot. Seeset_yscale() fordetails.

nonposy:{‘mask’ | ‘clip’} str

Non-positive values iny can be masked asinvalid, or clipped to a very small positive number.

Returns:

Line2D

Line instance of the plot.

Other Parameters:
 

kwargs :Line2D properties,

===================================================================================== ===============================================================================================================================================

Property Description

===================================================================================== ===============================================================================================================================================

:meth:`agg_filter <matplotlib.artist.Artist.set_agg_filter>` unknown

:meth:`alpha <matplotlib.artist.Artist.set_alpha>` float (0.0 transparent through 1.0 opaque)

:meth:`animated <matplotlib.artist.Artist.set_animated>` [True | False]

:meth:`antialiased <matplotlib.lines.Line2D.set_antialiased>` or aa [True | False]

:meth:`axes <matplotlib.artist.Artist.set_axes>` an :class:`~matplotlib.axes.Axes` instance

:meth:`clip_box <matplotlib.artist.Artist.set_clip_box>` a :class:`matplotlib.transforms.Bbox` instance

:meth:`clip_on <matplotlib.artist.Artist.set_clip_on>` [True | False]

:meth:`clip_path <matplotlib.artist.Artist.set_clip_path>` [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]

:meth:`color <matplotlib.lines.Line2D.set_color>` or c any matplotlib color

:meth:`contains <matplotlib.artist.Artist.set_contains>` a callable function

:meth:`dash_capstyle <matplotlib.lines.Line2D.set_dash_capstyle>` [‘butt’ | ‘round’ | ‘projecting’]

:meth:`dash_joinstyle <matplotlib.lines.Line2D.set_dash_joinstyle>` [‘miter’ | ‘round’ | ‘bevel’]

:meth:`dashes <matplotlib.lines.Line2D.set_dashes>` sequence of on/off ink in points

:meth:`drawstyle <matplotlib.lines.Line2D.set_drawstyle>` [‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]

:meth:`figure <matplotlib.artist.Artist.set_figure>` a :class:`matplotlib.figure.Figure` instance

:meth:`fillstyle <matplotlib.lines.Line2D.set_fillstyle>` [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]

:meth:`gid <matplotlib.artist.Artist.set_gid>` an id string

:meth:`label <matplotlib.artist.Artist.set_label>` string or anything printable with ‘%s’ conversion.

:meth:`linestyle <matplotlib.lines.Line2D.set_linestyle>` or ls [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) | ``’-‘`` | ``’–’`` | ``’-.’`` | ``’:’`` | ``’None’`` | ``’ ‘`` | ``’‘``]

:meth:`linewidth <matplotlib.lines.Line2D.set_linewidth>` or lw float value in points

:meth:`marker <matplotlib.lines.Line2D.set_marker>` :mod:`A valid marker style <matplotlib.markers>`

:meth:`markeredgecolor <matplotlib.lines.Line2D.set_markeredgecolor>` or mec any matplotlib color

:meth:`markeredgewidth <matplotlib.lines.Line2D.set_markeredgewidth>` or mew float value in points

:meth:`markerfacecolor <matplotlib.lines.Line2D.set_markerfacecolor>` or mfc any matplotlib color

:meth:`markerfacecoloralt <matplotlib.lines.Line2D.set_markerfacecoloralt>` or mfcalt any matplotlib color

:meth:`markersize <matplotlib.lines.Line2D.set_markersize>` or ms float

:meth:`markevery <matplotlib.lines.Line2D.set_markevery>` [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]

:meth:`path_effects <matplotlib.artist.Artist.set_path_effects>` unknown

:meth:`picker <matplotlib.lines.Line2D.set_picker>` float distance in points or callable pick function ``fn(artist, event)``

:meth:`pickradius <matplotlib.lines.Line2D.set_pickradius>` float distance in points

:meth:`rasterized <matplotlib.artist.Artist.set_rasterized>` [True | False | None]

:meth:`sketch_params <matplotlib.artist.Artist.set_sketch_params>` unknown

:meth:`snap <matplotlib.artist.Artist.set_snap>` unknown

:meth:`solid_capstyle <matplotlib.lines.Line2D.set_solid_capstyle>` [‘butt’ | ‘round’ | ‘projecting’]

:meth:`solid_joinstyle <matplotlib.lines.Line2D.set_solid_joinstyle>` [‘miter’ | ‘round’ | ‘bevel’]

:meth:`transform <matplotlib.lines.Line2D.set_transform>` a :class:`matplotlib.transforms.Transform` instance

:meth:`url <matplotlib.artist.Artist.set_url>` a url string

:meth:`visible <matplotlib.artist.Artist.set_visible>` [True | False]

:meth:`xdata <matplotlib.lines.Line2D.set_xdata>` 1D array

:meth:`ydata <matplotlib.lines.Line2D.set_ydata>` 1D array

:meth:`zorder <matplotlib.artist.Artist.set_zorder>` any number

===================================================================================== ===============================================================================================================================================

See also

loglog()
For example code and figure.
matplotlib.pyplot.set_cmap(cmap)

Set the default colormap. Applies to the current image if any.See help(colormaps) for more information.

cmap must be aColormap instance, orthe name of a registered colormap.

Seematplotlib.cm.register_cmap() andmatplotlib.cm.get_cmap().

matplotlib.pyplot.setp(*args,**kwargs)

Set a property on an artist object.

matplotlib supports the use ofsetp() (“set property”) andgetp() to set and get object properties, as well as to dointrospection on the object. For example, to set the linestyle of aline to be dashed, you can do:

>>>line,=plot([1,2,3])>>>setp(line,linestyle='--')

If you want to know the valid types of arguments, you can provide thename of the property you want to set without a value:

>>>setp(line,'linestyle')    linestyle: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' ]

If you want to see all the properties that can be set, and theirpossible values, you can do:

>>>setp(line)    ... long output listing omitted

setp() operates on a single instance or a list of instances.If you are in query mode introspecting the possible values, onlythe first instance in the sequence is used. When actually settingvalues, all the instances will be set. e.g., suppose you have alist of two lines, the following will make both lines thicker andred:

>>>x=arange(0,1.0,0.01)>>>y1=sin(2*pi*x)>>>y2=sin(4*pi*x)>>>lines=plot(x,y1,x,y2)>>>setp(lines,linewidth=2,color='r')

setp() works with the MATLAB style string/value pairs orwith python kwargs. For example, the following are equivalent:

>>>setp(lines,'linewidth',2,'color','r')# MATLAB style>>>setp(lines,linewidth=2,color='r')# python style
matplotlib.pyplot.show(*args,**kw)

Display a figure.When running in ipython with its pylab mode, display allfigures and return to the ipython prompt.

In non-interactive mode, display all figures and block untilthe figures have been closed; in interactive mode it has noeffect unless figures were created prior to a change fromnon-interactive to interactive mode (not recommended). Inthat case it displays the figures but does not block.

A single experimental keyword argument,block, may beset to True or False to override the blocking behaviordescribed above.

matplotlib.pyplot.specgram(x,NFFT=None,Fs=None,Fc=None,detrend=None,window=None,noverlap=None,cmap=None,xextent=None,pad_to=None,sides=None,scale_by_freq=None,mode=None,scale=None,vmin=None,vmax=None,hold=None,data=None,**kwargs)

Plot a spectrogram.

Call signature:

specgram(x,NFFT=256,Fs=2,Fc=0,detrend=mlab.detrend_none,window=mlab.window_hanning,noverlap=128,cmap=None,xextent=None,pad_to=None,sides='default',scale_by_freq=None,mode='default',scale='default',**kwargs)

Compute and plot a spectrogram of data inx. Data are split intoNFFT length segments and the spectrum of each section iscomputed. The windowing functionwindow is applied to eachsegment, and the amount of overlap of each segment isspecified withnoverlap. The spectrogram is plotted as a colormap(using imshow).

Parameters:

x : 1-D array or sequence

Array or sequence containing the data.

Fs : scalar

The sampling frequency (samples per time unit). It is usedto calculate the Fourier frequencies, freqs, in cycles per timeunit. The default value is 2.

window : callable or ndarray

A function or a vector of lengthNFFT. To create windowvectors seewindow_hanning(),window_none(),numpy.blackman(),numpy.hamming(),numpy.bartlett(),scipy.signal(),scipy.signal.get_window(), etc. The default iswindow_hanning(). If a function is passed as theargument, it must take a data segment as an argument andreturn the windowed version of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ]

Specifies which sides of the spectrum to return. Default gives thedefault behavior, which returns one-sided for real data and bothfor complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad_to : integer

The number of points to which the data segment is padded whenperforming the FFT. This can be different fromNFFT, whichspecifies the number of data points used. While not increasingthe actual resolution of the spectrum (the minimum distance betweenresolvable peaks), this can give more points in the plot,allowing for more detail. This corresponds to then parameterin the call to fft(). The default is None, which setspad_toequal toNFFT

NFFT : integer

The number of data points used in each block for the FFT.A power 2 is most efficient. The default value is 256.This shouldNOT be used to get zero padding, or the scaling of theresult will be incorrect. Usepad_to for this instead.

detrend : {‘default’, ‘constant’, ‘mean’, ‘linear’, ‘none’} or callable

The function applied to each segment before fft-ing,designed to remove the mean or linear trend. Unlike inMATLAB, where thedetrend parameter is a vector, inmatplotlib is it a function. Thepylabmodule definesdetrend_none(),detrend_mean(), anddetrend_linear(), but you can usea custom function as well. You can also use a string to chooseone of the functions. ‘default’, ‘constant’, and ‘mean’ calldetrend_mean(). ‘linear’ callsdetrend_linear(). ‘none’ callsdetrend_none().

scale_by_freq : boolean, optional

Specifies whether the resulting density values should be scaledby the scaling frequency, which gives density in units of Hz^-1.This allows for integration over the returned frequency values.The default is True for MATLAB compatibility.

mode : [ ‘default’ | ‘psd’ | ‘magnitude’ | ‘angle’ | ‘phase’ ]

What sort of spectrum to use. Default is ‘psd’, which takesthe power spectral density. ‘complex’ returns the complex-valuedfrequency spectrum. ‘magnitude’ returns the magnitude spectrum.‘angle’ returns the phase spectrum without unwrapping. ‘phase’returns the phase spectrum with unwrapping.

noverlap : integer

The number of points of overlap between blocks. Thedefault value is 128.

scale : [ ‘default’ | ‘linear’ | ‘dB’ ]

The scaling of the values in thespec. ‘linear’ is no scaling.‘dB’ returns the values in dB scale. Whenmode is ‘psd’,this is dB power (10 * log10). Otherwise this is dB amplitude(20 * log10). ‘default’ is ‘dB’ ifmode is ‘psd’ or‘magnitude’ and ‘linear’ otherwise. This must be ‘linear’ifmode is ‘angle’ or ‘phase’.

Fc : integer

The center frequency ofx (defaults to 0), which offsetsthe x extents of the plot to reflect the frequency range usedwhen a signal is acquired and then filtered and downsampled tobaseband.

cmap :

Amatplotlib.colors.Colormap instance; ifNone, usedefault determined by rc

xextent : [None | (xmin, xmax)]

The image extent along the x-axis. The default setsxmin to theleft border of the first bin (spectrum column) andxmax to theright border of the last bin. Note that fornoverlap>0 the widthof the bins is smaller than those of the segments.

**kwargs :

Additional kwargs are passed on to imshow which makes thespecgram image

Returns:

spectrum : 2-D array

Columns are the periodograms of successive segments.

freqs : 1-D array

The frequencies corresponding to the rows inspectrum.

t : 1-D array

The times corresponding to midpoints of segments (i.e., the columnsinspectrum).

im : instance of classAxesImage

The image created by imshow containing the spectrogram

See also

psd()
psd() differs in the default overlap; in returning the mean of the segment periodograms; in not returning times; and in generating a line plot instead of colormap.
magnitude_spectrum()
A single spectrum, similar to having a single segment whenmode is ‘magnitude’. Plots a line instead of a colormap.
angle_spectrum()
A single spectrum, similar to having a single segment whenmode is ‘angle’. Plots a line instead of a colormap.
phase_spectrum()
A single spectrum, similar to having a single segment whenmode is ‘phase’. Plots a line instead of a colormap.
In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, the following arguments are replaced bydata[<arg>]: * All arguments with the following names: ‘x’.

Notes

detrend andscale_by_freq only apply whenmode is set to‘psd’

Examples

(Source code,png,pdf)

../_images/specgram_demo2.png
matplotlib.pyplot.spectral()

set the default colormap to spectral and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.spring()

set the default colormap to spring and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.spy(Z,precision=0,marker=None,markersize=None,aspect='equal',**kwargs)

Plot the sparsity pattern on a 2-D array.

spy(Z) plots the sparsity pattern of the 2-D arrayZ.

Parameters:

Z : sparse array (n, m)

The array to be plotted.

precision : float, optional, default: 0

Ifprecision is 0, any non-zero value will be plotted; else,values of will be plotted.

Forscipy.sparse.spmatrix instances, there is a specialcase: ifprecision is ‘present’, any value present in the arraywill be plotted, even if it is identically zero.

origin : [“upper”, “lower”], optional, default: “upper”

Place the [0,0] index of the array in the upper left or lower leftcorner of the axes.

aspect : [‘auto’ | ‘equal’ | scalar], optional, default: “equal”

If ‘equal’, andextent is None, changes the axes aspect ratio tomatch that of the image. Ifextent is notNone, the axesaspect ratio is changed to match that of the extent.

If ‘auto’, changes the image aspect ratio to match that of theaxes.

If None, default to rcimage.aspect value.

Two plotting styles are available: image or marker. Both

are available for full arrays, but only the marker style

works for :class:`scipy.sparse.spmatrix` instances.

If *marker* and *markersize* are *None*, an image will be

returned and any remaining kwargs are passed to

:func:`~matplotlib.pyplot.imshow`; else, a

:class:`~matplotlib.lines.Line2D` object will be returned with

the value of marker determining the marker type, and any

remaining kwargs passed to the

:meth:`~matplotlib.axes.Axes.plot` method.

If *marker* and *markersize* are *None*, useful kwargs include:

* *cmap*

* *alpha*

See also

imshow
for image options.
plot
for plotting options
matplotlib.pyplot.stackplot(x,*args,**kwargs)

Draws a stacked area plot.

x : 1d array of dimension N

y:2d array of dimension MxN, OR any number 1d arrays each of dimension

1xN. The data is assumed to be unstacked. Each of the followingcalls is legal:

stackplot(x,y)# where y is MxNstackplot(x,y1,y2,y3,y4)# where y1, y2, y3, y4, are all 1xNm

Keyword arguments:

baseline:[‘zero’, ‘sym’, ‘wiggle’, ‘weighted_wiggle’]
Method used to calculate the baseline. ‘zero’ is just asimple stacked plot. ‘sym’ is symmetric around zero andis sometimes calledThemeRiver. ‘wiggle’ minimizes thesum of the squared slopes. ‘weighted_wiggle’ does thesame but weights to account for size of each layer.It is also calledStreamgraph-layout. More detailscan be found athttp://leebyron.com/streamgraph/.

labels : A list or tuple of labels to assign to each data series.

colors:A list or tuple of colors. These will be cycled through and
used to colour the stacked areas.All other keyword arguments are passed tofill_between()

Returnsr : A list ofPolyCollection, one for eachelement in the stacked area plot.

matplotlib.pyplot.stem(*args,**kwargs)

Create a stem plot.

Call signatures:

stem(y,linefmt='b-',markerfmt='bo',basefmt='r-')stem(x,y,linefmt='b-',markerfmt='bo',basefmt='r-')

A stem plot plots vertical lines (usinglinefmt) at eachxlocation from the baseline toy, and places a marker thereusingmarkerfmt. A horizontal line at 0 is is plotted usingbasefmt.

If nox values are provided, the default is (0, 1, ..., len(y) - 1)

Return value is a tuple (markerline,stemlines,baseline).

See also

Thisdocumentfor details.

Example:

(Source code,png,pdf)

../_images/stem_plot2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All positional and all keyword arguments.
matplotlib.pyplot.step(x,y,*args,**kwargs)

Make a step plot.

Parameters:

x : array_like

1-D sequence, and it is assumed, but not checked,that it is uniformly increasing.

y : array_like

1-D sequence, and it is assumed, but not checked,that it is uniformly increasing.

Returns:

list

List of lines that were added.

Other Parameters:
 

where : [ ‘pre’ | ‘post’ | ‘mid’ ]

If ‘pre’ (the default), the interval fromx[i] to x[i+1] has level y[i+1].

If ‘post’, that interval has level y[i].

If ‘mid’, the jumps iny occur half-way between thex-values.

Notes

Additional parameters are the same as those forplot().

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’, ‘y’.
matplotlib.pyplot.streamplot(x,y,u,v,density=1,linewidth=None,color=None,cmap=None,norm=None,arrowsize=1,arrowstyle='-|>',minlength=0.1,transform=None,zorder=None,start_points=None,hold=None,data=None)

Draws streamlines of a vector flow.

x,y:1d arrays
anevenly spaced grid.
u,v:2d arrays
x and y-velocities. Number of rows should match length of y, andthe number of columns should match x.
density:float or 2-tuple
Controls the closeness of streamlines. Whendensity=1, the domainis divided into a 30x30 grid—density linearly scales this grid.Each cell in the grid can have, at most, one traversing streamline.For different densities in each direction, use [density_x, density_y].
linewidth:numeric or 2d array
vary linewidth when given a 2d array with the same shape as velocities.
color:matplotlib color code, or 2d array
Streamline color. When given an array with the same shape asvelocities,color values are converted to colors usingcmap.
cmap:Colormap
Colormap used to plot streamlines and arrows. Only necessary when usingan array input forcolor.
norm:Normalize
Normalize object used to scale luminance data to 0, 1. If None, stretch(min, max) to (0, 1). Only necessary whencolor is an array.
arrowsize:float
Factor scale arrow size.
arrowstyle:str
Arrow style specification.SeeFancyArrowPatch.
minlength:float
Minimum length of streamline in axes coordinates.
start_points: Nx2 array
Coordinates of starting points for the streamlines.In data coordinates, the same as thex andy arrays.
zorder:int
any number

Returns:

stream_container:StreamplotSet

Container object with attributes

This container will probably change in the future to allow changesto the colormap, alpha, etc. for both lines and arrows, but thesechanges should be backward compatible.

matplotlib.pyplot.subplot(*args,**kwargs)

Return a subplot axes positioned by the given grid definition.

Typical call signature:

subplot(nrows,ncols,plot_number)

Wherenrows andncols are used to notionally split the figureintonrows*ncols sub-axes, andplot_number is used to identifythe particular subplot that this function is to create within the notionalgrid.plot_number starts at 1, increments across rows first and has amaximum ofnrows*ncols.

In the case whennrows,ncols andplot_number are all less than 10,a convenience exists, such that the a 3 digit number can be given instead,where the hundreds representnrows, the tens representncols and theunits representplot_number. For instance:

subplot(211)

produces a subaxes in a figure which represents the top plot (i.e. thefirst) in a 2 row by 1 column notional grid (no grid actually exists,but conceptually this is how the returned subplot has been positioned).

Note

Creating a subplot will delete any pre-existing subplot that overlapswith it beyond sharing a boundary:

importmatplotlib.pyplotasplt# plot a line, implicitly creating a subplot(111)plt.plot([1,2,3])# now create a subplot which represents the top plot of a grid# with 2 rows and 1 column. Since this subplot will overlap the# first, the plot (and its axes) previously created, will be removedplt.subplot(211)plt.plot(range(12))plt.subplot(212,facecolor='y')# creates 2nd subplot with yellow background

If you do not want this behavior, use theadd_subplot() method or theaxes() function instead.

Keyword arguments:

facecolor:
The background color of the subplot, which can be any validcolor specifier. Seematplotlib.colors for moreinformation.
polar:
A boolean flag indicating whether the subplot plot should bea polar projection. Defaults toFalse.
projection:
A string giving the name of a custom projection to be usedfor the subplot. This projection must have been previouslyregistered. Seematplotlib.projections.

See also

axes()
For additional information onaxes() andsubplot() keyword arguments.
examples/pie_and_polar_charts/polar_scatter_demo.py
For an example

Example:

(Source code,png,pdf)

../_images/subplot_demo3.png
matplotlib.pyplot.subplot2grid(shape,loc,rowspan=1,colspan=1,**kwargs)

Create a subplot in a grid. The grid is specified byshape, atlocation ofloc, spanningrowspan,colspan cells in eachdirection. The index for loc is 0-based.

subplot2grid(shape,loc,rowspan=1,colspan=1)

is identical to

gridspec=GridSpec(shape[0],shape[1])subplotspec=gridspec.new_subplotspec(loc,rowspan,colspan)subplot(subplotspec)
matplotlib.pyplot.subplot_tool(targetfig=None)

Launch a subplot tool window for a figure.

Amatplotlib.widgets.SubplotTool instance is returned.

matplotlib.pyplot.subplots(nrows=1,ncols=1,sharex=False,sharey=False,squeeze=True,subplot_kw=None,gridspec_kw=None,**fig_kw)

Create a figure and a set of subplots

This utility wrapper makes it convenient to create common layouts ofsubplots, including the enclosing figure object, in a single call.

Parameters:

nrows, ncols : int, optional, default: 1

Number of rows/columns of the subplot grid.

sharex, sharey : bool or {‘none’, ‘all’, ‘row’, ‘col’}, default: False

Controls sharing of properties among x (sharex) or y (sharey)axes:

  • True or ‘all’: x- or y-axis will be shared among allsubplots.
  • False or ‘none’: each subplot x- or y-axis will beindependent.
  • ‘row’: each subplot row will share an x- or y-axis.
  • ‘col’: each subplot column will share an x- or y-axis.

When subplots have a shared x-axis along a column, only the x ticklabels of the bottom subplot are visible. Similarly, when subplotshave a shared y-axis along a row, only the y tick labels of the firstcolumn subplot are visible.

squeeze : bool, optional, default: True

  • If True, extra dimensions are squeezed out from the returned Axesobject:

    • if only one subplot is constructed (nrows=ncols=1), theresulting single Axes object is returned as a scalar.
    • for Nx1 or 1xN subplots, the returned object is a 1D numpyobject array of Axes objects are returned as numpy 1D arrays.
    • for NxM, subplots with N>1 and M>1 are returned as a 2D arrays.
  • If False, no squeezing at all is done: the returned Axes object isalways a 2D array containing Axes instances, even if it ends upbeing 1x1.

subplot_kw : dict, optional

Dict with keywords passed to theadd_subplot() call used to create eachsubplot.

gridspec_kw : dict, optional

Dict with keywords passed to theGridSpec constructor used to create thegrid the subplots are placed on.

**fig_kw :

All additional keyword arguments are passed to thefigure() call.

Returns:

fig :matplotlib.figure.Figure object

ax : Axes object or array of Axes objects.

ax can be either a singlematplotlib.axes.Axes object or anarray of Axes objects if more than one subplot was created. Thedimensions of the resulting array can be controlled with the squeezekeyword, see above.

See also

figure,subplot

Examples

First create some toy data:

>>>x=np.linspace(0,2*np.pi,400)>>>y=np.sin(x**2)

Creates just a figure and only one subplot

>>>fig,ax=plt.subplots()>>>ax.plot(x,y)>>>ax.set_title('Simple plot')

Creates two subplots and unpacks the output array immediately

>>>f,(ax1,ax2)=plt.subplots(1,2,sharey=True)>>>ax1.plot(x,y)>>>ax1.set_title('Sharing Y axis')>>>ax2.scatter(x,y)

Creates four polar axes, and accesses them through the returned array

>>>fig,axes=plt.subplots(2,2,subplot_kw=dict(polar=True))>>>axes[0,0].plot(x,y)>>>axes[1,1].scatter(x,y)

Share a X axis with each column of subplots

>>>plt.subplots(2,2,sharex='col')

Share a Y axis with each row of subplots

>>>plt.subplots(2,2,sharey='row')

Share both X and Y axes with all subplots

>>>plt.subplots(2,2,sharex='all',sharey='all')

Note that this is the same as

>>>plt.subplots(2,2,sharex=True,sharey=True)
matplotlib.pyplot.subplots_adjust(*args,**kwargs)

Tune the subplot layout.

call signature:

subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)

The parameter meanings (and suggested defaults) are:

left=0.125# the left side of the subplots of the figureright=0.9# the right side of the subplots of the figurebottom=0.1# the bottom of the subplots of the figuretop=0.9# the top of the subplots of the figurewspace=0.2# the amount of width reserved for blank space between subplots,# expressed as a fraction of the average axis widthhspace=0.2# the amount of height reserved for white space between subplots,# expressed as a fraction of the average axis height

The actual defaults are controlled by the rc file

matplotlib.pyplot.summer()

set the default colormap to summer and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.suptitle(*args,**kwargs)

Add a centered title to the figure.

kwargs arematplotlib.text.Text properties. Using figurecoordinates, the defaults are:

x:0.5
The x location of the text in figure coords
y:0.98
The y location of the text in figure coords
horizontalalignment:‘center’
The horizontal alignment of the text
verticalalignment:‘top’
The vertical alignment of the text

If thefontproperties keyword argument is given then thercParams defaults forfontsize (figure.titlesize) andfontweight (figure.titleweight) will be ignored in favourof theFontProperties defaults.

Amatplotlib.text.Text instance is returned.

Example:

fig.suptitle('this is the figure title',fontsize=12)
matplotlib.pyplot.switch_backend(newbackend)

Switch the default backend. This feature isexperimental, andis only expected to work switching to an image backend. e.g., ifyou have a bunch of PostScript scripts that you want to run froman interactive ipython session, you may want to switch to the PSbackend before running them to avoid having a bunch of GUI windowspopup. If you try to interactively switch from one GUI backend toanother, you will explode.

Calling this command will close all open windows.

matplotlib.pyplot.table(**kwargs)

Add a table to the current axes.

Call signature:

table(cellText=None,cellColours=None,cellLoc='right',colWidths=None,rowLabels=None,rowColours=None,rowLoc='left',colLabels=None,colColours=None,colLoc='center',loc='bottom',bbox=None):

Returns amatplotlib.table.Table instance. EithercellTextorcellColours must be provided. For finer grained control overtables, use theTable class and add it tothe axes withadd_table().

Thanks to John Gill for providing the class and table.

kwargs control theTableproperties:

PropertyDescription
agg_filterunknown
alphafloat (0.0 transparent through 1.0 opaque)
animated[True | False]
axesanAxes instance
clip_boxamatplotlib.transforms.Bbox instance
clip_on[True | False]
clip_path[ (Path,Transform) |Patch | None ]
containsa callable function
figureamatplotlib.figure.Figure instance
fontsizea float in points
gidan id string
labelstring or anything printable with ‘%s’ conversion.
path_effectsunknown
picker[None|float|boolean|callable]
rasterized[True | False | None]
sketch_paramsunknown
snapunknown
transformTransform instance
urla url string
visible[True | False]
zorderany number
matplotlib.pyplot.text(x,y,s,fontdict=None,withdash=False,**kwargs)

Add text to the axes.

Add text in strings to axis at locationx,y, datacoordinates.

Parameters:

x, y : scalars

data coordinates

s : string

text

fontdict : dictionary, optional, default: None

A dictionary to override the default text properties. If fontdictis None, the defaults are determined by your rc parameters.

withdash : boolean, optional, default: False

Creates aTextWithDash instance instead of aText instance.

Other Parameters:
 

kwargs :Text properties.

Other miscellaneous text parameters.

Examples

Individual keyword arguments can be used to override any givenparameter:

>>>text(x,y,s,fontsize=12)

The default transform specifies that text is in data coords,alternatively, you can specify text in axis coords (0,0 islower-left and 1,1 is upper-right). The example below placestext in the center of the axes:

>>>text(0.5,0.5,'matplotlib',horizontalalignment='center',...verticalalignment='center',...transform=ax.transAxes)

You can put a rectangular box around the text instance (e.g., toset a background color) by using the keywordbbox.bbox isa dictionary ofRectangleproperties. For example:

>>>text(x,y,s,bbox=dict(facecolor='red',alpha=0.5))
matplotlib.pyplot.thetagrids(*args,**kwargs)

Get or set the theta locations of the gridlines in a polar plot.

If no arguments are passed, return a tuple (lines,labels)wherelines is an array of radial gridlines(Line2D instances) andlabels is anarray of tick labels (Text instances):

lines,labels=thetagrids()

Otherwise the syntax is:

lines,labels=thetagrids(angles,labels=None,fmt='%d',frac=1.1)

set the angles at which to place the theta grids (these gridlinesare equal along the theta dimension).

angles is in degrees.

labels, if notNone, is a len(angles) list of strings of thelabels to use at each angle.

Iflabels isNone, the labels will befmt%angle.

frac is the fraction of the polar axes radius at which to placethe label (1 is the edge). e.g., 1.05 is outside the axes and 0.95is inside the axes.

Return value is a list of tuples (lines,labels):

  • lines areLine2D instances
  • labels areText instances.

Note that on input, thelabels argument is a list of strings,and on output it is a list ofTextinstances.

Examples:

# set the locations of the radial gridlines and labelslines,labels=thetagrids(range(45,360,90))# set the locations and labels of the radial gridlines and labelslines,labels=thetagrids(range(45,360,90),('NE','NW','SW','SE'))
matplotlib.pyplot.tick_params(axis='both',**kwargs)

Change the appearance of ticks and tick labels.

Parameters:

axis : {‘x’, ‘y’, ‘both’}, optional

Which axis to apply the parameters to.

Other Parameters:
 

axis : {‘x’, ‘y’, ‘both’}

Axis on which to operate; default is ‘both’.

reset : bool

IfTrue, set all parameters to defaultsbefore processing other keyword arguments. Default isFalse.

which : {‘major’, ‘minor’, ‘both’}

Default is ‘major’; apply arguments towhich ticks.

direction : {‘in’, ‘out’, ‘inout’}

Puts ticks inside the axes, outside the axes, or both.

length : float

Tick length in points.

width : float

Tick width in points.

color : color

Tick color; accepts any mpl color spec.

pad : float

Distance in points between tick and label.

labelsize : float or str

Tick label font size in points or as a string (e.g., ‘large’).

labelcolor : color

Tick label color; mpl color spec.

colors : color

Changes the tick color and the label color to the same value:mpl color spec.

zorder : float

Tick and label zorder.

bottom, top, left, right : bool or {‘on’, ‘off’}

controls whether to draw the respective ticks.

labelbottom, labeltop, labelleft, labelright : bool or {‘on’, ‘off’}

controls whether to draw therespective tick labels.

Examples

Usage

ax.tick_params(direction='out',length=6,width=2,colors='r')

This will make all major ticks be red, pointing out of the box,and with dimensions 6 points by 2 points. Tick labels willalso be red.

matplotlib.pyplot.ticklabel_format(**kwargs)

Change theScalarFormatter used bydefault for linear axes.

Optional keyword arguments:

KeywordDescription
style[ ‘sci’ (or ‘scientific’) | ‘plain’ ]plain turns off scientific notation
scilimits(m, n), pair of integers; ifstyleis ‘sci’, scientific notation willbe used for numbers outside the range10`m`:sup: to 10`n`:sup:.Use (0,0) to include all numbers.
useOffset[True | False | offset]; if True,the offset will be calculated as needed;if False, no offset will be used; if anumeric offset is specified, it will beused.
axis[ ‘x’ | ‘y’ | ‘both’ ]
useLocaleIf True, format the number according tothe current locale. This affects thingssuch as the character used for thedecimal separator. If False, useC-style (English) formatting. Thedefault setting is controlled by theaxes.formatter.use_locale rcparam.

Only the major ticks are affected.If the method is called when theScalarFormatter is not theFormatter being used, anAttributeError will be raised.

matplotlib.pyplot.tight_layout(pad=1.08,h_pad=None,w_pad=None,rect=None)

Automatically adjust subplot parameters to give specified padding.

Parameters:

pad:float
padding between the figure edge and the edges of subplots, as a fraction of the font-size.
h_pad, w_pad:float
padding (height/width) between edges of adjacent subplots.Defaults topad_inches.
rect:if rect is given, it is interpreted as a rectangle
(left, bottom, right, top) in the normalized figurecoordinate that the whole subplots area (includinglabels) will fit into. Default is (0, 0, 1, 1).
matplotlib.pyplot.title(s,*args,**kwargs)

Set a title of the current axes.

Set one of the three available axes titles. The available titles arepositioned above the axes in the center, flush with the left edge,and flush with the right edge.

See also

Seetext() for adding textto the current axes

Parameters:

label : str

Text to use for the title

fontdict : dict

A dictionary controlling the appearance of the title text,the defaultfontdict is:

{‘fontsize’: rcParams[‘axes.titlesize’],‘fontweight’ : rcParams[‘axes.titleweight’],‘verticalalignment’: ‘baseline’,‘horizontalalignment’: loc}

loc : {‘center’, ‘left’, ‘right’}, str, optional

Which title to set, defaults to ‘center’

Returns:

text :Text

The matplotlib text instance representing the title

Other Parameters:
 

kwargs : text properties

Other keyword arguments are text properties, seeText for a list of valid textproperties.

matplotlib.pyplot.tricontour(*args,**kwargs)

Draw contours on an unstructured triangular grid.tricontour() andtricontourf() draw contour lines andfilled contours, respectively. Except as noted, functionsignatures and return values are the same for both versions.

The triangulation can be specified in one of two ways; either:

tricontour(triangulation,...)

where triangulation is amatplotlib.tri.Triangulationobject, or

tricontour(x,y,...)tricontour(x,y,triangles,...)tricontour(x,y,triangles=triangles,...)tricontour(x,y,mask=mask,...)tricontour(x,y,triangles,mask=mask,...)

in which case a Triangulation object will be created. SeeTriangulation for a explanation ofthese possibilities.

The remaining arguments may be:

tricontour(...,Z)

whereZ is the array of values to contour, one per pointin the triangulation. The level values are chosenautomatically.

tricontour(...,Z,N)

contourN automatically-chosen levels.

tricontour(...,Z,V)

draw contour lines at the values specified in sequenceV,which must be in increasing order.

tricontourf(...,Z,V)

fill the (len(V)-1) regions between the values inV,which must be in increasing order.

tricontour(Z,**kwargs)

Use keyword args to control colors, linewidth, origin, cmap ... seebelow for more details.

C=tricontour(...) returns aTriContourSet object.

Optional keyword arguments:

colors: [None | string | (mpl_colors) ]

IfNone, the colormap specified by cmap will be used.

If a string, like ‘r’ or ‘red’, all levels will be plotted in thiscolor.

If a tuple of matplotlib color args (string, float, rgb, etc),different levels will be plotted in different colors in the orderspecified.

alpha: float
The alpha blending value
cmap: [None | Colormap ]
A cmColormap instance orNone. Ifcmap isNone andcolors isNone, adefault Colormap is used.
norm: [None | Normalize ]
Amatplotlib.colors.Normalize instance forscaling data values to colors. Ifnorm isNone andcolors isNone, the default linear scaling is used.
levels [level0, level1, ..., leveln]
A list of floating point numbers indicating the levelcurves to draw, in increasing order; e.g., to draw justthe zero contour passlevels=[0]
origin: [None | ‘upper’ | ‘lower’ | ‘image’ ]

IfNone, the first value ofZ will correspond to thelower left corner, location (0,0). If ‘image’, the rcvalue forimage.origin will be used.

This keyword is not active ifX andY are specified inthe call to contour.

extent: [None | (x0,x1,y0,y1) ]

Iforigin is notNone, thenextent is interpreted asinmatplotlib.pyplot.imshow(): it gives the outerpixel boundaries. In this case, the position of Z[0,0]is the center of the pixel, not a corner. Iforigin isNone, then (x0,y0) is the position of Z[0,0], and(x1,y1) is the position of Z[-1,-1].

This keyword is not active ifX andY are specified inthe call to contour.

locator: [None | ticker.Locator subclass ]
Iflocator is None, the defaultMaxNLocator is used. Thelocator is used to determine the contour levels if theyare not given explicitly via theV argument.
extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
Unless this is ‘neither’, contour levels are automaticallyadded to one or both ends of the range so that all dataare included. These added ranges are then mapped to thespecial colormap values which default to the ends of thecolormap range, but can be set viamatplotlib.colors.Colormap.set_under() andmatplotlib.colors.Colormap.set_over() methods.
xunits,yunits: [None | registered units ]
Override axis units by specifying an instance of amatplotlib.units.ConversionInterface.

tricontour-only keyword arguments:

linewidths: [None | number | tuple of numbers ]

Iflinewidths isNone, the default width inlines.linewidth inmatplotlibrc is used.

If a number, all levels will be plotted with this linewidth.

If a tuple, different levels will be plotted with differentlinewidths in the order specified

linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ]

Iflinestyles isNone, the ‘solid’ is used.

linestyles can also be an iterable of the above stringsspecifying a set of linestyles to be used. If thisiterable is shorter than the number of contour levelsit will be repeated as necessary.

If contour is using a monochrome colormap and the contourlevel is less than 0, then the linestyle specifiedincontour.negative_linestyle inmatplotlibrcwill be used.

tricontourf-only keyword arguments:

antialiased: [True |False ]
enable antialiasing

Note: tricontourf fills intervals that are closed at the top; thatis, for boundariesz1 andz2, the filled region is:

z1<z<=z2

There is one exception: if the lowest boundary coincides withthe minimum value of thez array, then that minimum valuewill be included in the lowest interval.

Examples:

(Source code)

matplotlib.pyplot.tricontourf(*args,**kwargs)

Draw contours on an unstructured triangular grid.tricontour() andtricontourf() draw contour lines andfilled contours, respectively. Except as noted, functionsignatures and return values are the same for both versions.

The triangulation can be specified in one of two ways; either:

tricontour(triangulation,...)

where triangulation is amatplotlib.tri.Triangulationobject, or

tricontour(x,y,...)tricontour(x,y,triangles,...)tricontour(x,y,triangles=triangles,...)tricontour(x,y,mask=mask,...)tricontour(x,y,triangles,mask=mask,...)

in which case a Triangulation object will be created. SeeTriangulation for a explanation ofthese possibilities.

The remaining arguments may be:

tricontour(...,Z)

whereZ is the array of values to contour, one per pointin the triangulation. The level values are chosenautomatically.

tricontour(...,Z,N)

contourN automatically-chosen levels.

tricontour(...,Z,V)

draw contour lines at the values specified in sequenceV,which must be in increasing order.

tricontourf(...,Z,V)

fill the (len(V)-1) regions between the values inV,which must be in increasing order.

tricontour(Z,**kwargs)

Use keyword args to control colors, linewidth, origin, cmap ... seebelow for more details.

C=tricontour(...) returns aTriContourSet object.

Optional keyword arguments:

colors: [None | string | (mpl_colors) ]

IfNone, the colormap specified by cmap will be used.

If a string, like ‘r’ or ‘red’, all levels will be plotted in thiscolor.

If a tuple of matplotlib color args (string, float, rgb, etc),different levels will be plotted in different colors in the orderspecified.

alpha: float
The alpha blending value
cmap: [None | Colormap ]
A cmColormap instance orNone. Ifcmap isNone andcolors isNone, adefault Colormap is used.
norm: [None | Normalize ]
Amatplotlib.colors.Normalize instance forscaling data values to colors. Ifnorm isNone andcolors isNone, the default linear scaling is used.
levels [level0, level1, ..., leveln]
A list of floating point numbers indicating the levelcurves to draw, in increasing order; e.g., to draw justthe zero contour passlevels=[0]
origin: [None | ‘upper’ | ‘lower’ | ‘image’ ]

IfNone, the first value ofZ will correspond to thelower left corner, location (0,0). If ‘image’, the rcvalue forimage.origin will be used.

This keyword is not active ifX andY are specified inthe call to contour.

extent: [None | (x0,x1,y0,y1) ]

Iforigin is notNone, thenextent is interpreted asinmatplotlib.pyplot.imshow(): it gives the outerpixel boundaries. In this case, the position of Z[0,0]is the center of the pixel, not a corner. Iforigin isNone, then (x0,y0) is the position of Z[0,0], and(x1,y1) is the position of Z[-1,-1].

This keyword is not active ifX andY are specified inthe call to contour.

locator: [None | ticker.Locator subclass ]
Iflocator is None, the defaultMaxNLocator is used. Thelocator is used to determine the contour levels if theyare not given explicitly via theV argument.
extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
Unless this is ‘neither’, contour levels are automaticallyadded to one or both ends of the range so that all dataare included. These added ranges are then mapped to thespecial colormap values which default to the ends of thecolormap range, but can be set viamatplotlib.colors.Colormap.set_under() andmatplotlib.colors.Colormap.set_over() methods.
xunits,yunits: [None | registered units ]
Override axis units by specifying an instance of amatplotlib.units.ConversionInterface.

tricontour-only keyword arguments:

linewidths: [None | number | tuple of numbers ]

Iflinewidths isNone, the default width inlines.linewidth inmatplotlibrc is used.

If a number, all levels will be plotted with this linewidth.

If a tuple, different levels will be plotted with differentlinewidths in the order specified

linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ]

Iflinestyles isNone, the ‘solid’ is used.

linestyles can also be an iterable of the above stringsspecifying a set of linestyles to be used. If thisiterable is shorter than the number of contour levelsit will be repeated as necessary.

If contour is using a monochrome colormap and the contourlevel is less than 0, then the linestyle specifiedincontour.negative_linestyle inmatplotlibrcwill be used.

tricontourf-only keyword arguments:

antialiased: [True |False ]
enable antialiasing

Note: tricontourf fills intervals that are closed at the top; thatis, for boundariesz1 andz2, the filled region is:

z1<z<=z2

There is one exception: if the lowest boundary coincides withthe minimum value of thez array, then that minimum valuewill be included in the lowest interval.

Examples:

(Source code)

matplotlib.pyplot.tripcolor(*args,**kwargs)

Create a pseudocolor plot of an unstructured triangular grid.

The triangulation can be specified in one of two ways; either:

tripcolor(triangulation,...)

where triangulation is amatplotlib.tri.Triangulationobject, or

tripcolor(x,y,...)tripcolor(x,y,triangles,...)tripcolor(x,y,triangles=triangles,...)tripcolor(x,y,mask=mask,...)tripcolor(x,y,triangles,mask=mask,...)

in which case a Triangulation object will be created. SeeTriangulation for a explanation of thesepossibilities.

The next argument must beC, the array of color values, eitherone per point in the triangulation if color values are defined atpoints, or one per triangle in the triangulation if color valuesare defined at triangles. If there are the same number of pointsand triangles in the triangulation it is assumed that colorvalues are defined at points; to force the use of color values attriangles use the kwargfacecolors*=C instead of just *C.

shading may be ‘flat’ (the default) or ‘gouraud’. Ifshadingis ‘flat’ and C values are defined at points, the color valuesused for each triangle are from the mean C of the triangle’sthree points. Ifshading is ‘gouraud’ then color values must bedefined at points.

The remaining kwargs are the same as forpcolor().

Example:

matplotlib.pyplot.triplot(*args,**kwargs)

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

The triangulation to plot can be specified in one of two ways;either:

triplot(triangulation,...)

where triangulation is amatplotlib.tri.Triangulationobject, or

triplot(x,y,...)triplot(x,y,triangles,...)triplot(x,y,triangles=triangles,...)triplot(x,y,mask=mask,...)triplot(x,y,triangles,mask=mask,...)

in which case a Triangulation object will be created. SeeTriangulation for a explanation of thesepossibilities.

The remaining args and kwargs are the same as forplot().

Return a list of 2Line2D containingrespectively:

  • the lines plotted for triangles edges
  • the markers plotted for triangles nodes

Example:

matplotlib.pyplot.twinx(ax=None)

Make a second axes that shares thex-axis. The new axes willoverlayax (or the current axes ifax isNone). The ticksforax2 will be placed on the right, and theax2 instance isreturned.

See also

examples/api_examples/two_scales.py
For an example
matplotlib.pyplot.twiny(ax=None)

Make a second axes that shares they-axis. The new axis willoverlayax (or the current axes ifax isNone). The ticksforax2 will be placed on the top, and theax2 instance isreturned.

matplotlib.pyplot.uninstall_repl_displayhook()

Uninstalls the matplotlib display hook.

matplotlib.pyplot.violinplot(dataset,positions=None,vert=True,widths=0.5,showmeans=False,showextrema=True,showmedians=False,points=100,bw_method=None,hold=None,data=None)

Make a violin plot.

Make a violin plot for each column ofdataset or each vector insequencedataset. Each filled area extends to represent theentire data range, with optional lines at the mean, the median,the minimum, and the maximum.

Parameters:

dataset : Array or a sequence of vectors.

The input data.

positions : array-like, default = [1, 2, ..., n]

Sets the positions of the violins. The ticks and limits areautomatically set to match the positions.

vert : bool, default = True.

If true, creates a vertical violin plot.Otherwise, creates a horizontal violin plot.

widths : array-like, default = 0.5

Either a scalar or a vector that sets the maximal width ofeach violin. The default is 0.5, which uses about half of theavailable horizontal space.

showmeans : bool, default = False

IfTrue, will toggle rendering of the means.

showextrema : bool, default = True

IfTrue, will toggle rendering of the extrema.

showmedians : bool, default = False

IfTrue, will toggle rendering of the medians.

points : scalar, default = 100

Defines the number of points to evaluate each of thegaussian kernel density estimations at.

bw_method : str, scalar or callable, optional

The method used to calculate the estimator bandwidth. This can be‘scott’, ‘silverman’, a scalar constant or a callable. If ascalar, this will be used directly askde.factor. If acallable, it should take aGaussianKDE instance as its onlyparameter and return a scalar. If None (default), ‘scott’ is used.

Returns:

result : dict

A dictionary mapping each component of the violinplot to alist of the corresponding collection instances created. Thedictionary has the following keys:

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘dataset’.
matplotlib.pyplot.viridis()

set the default colormap to viridis and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.vlines(x,ymin,ymax,colors='k',linestyles='solid',label='',hold=None,data=None,**kwargs)

Plot vertical lines.

Plot vertical lines at eachx fromymin toymax.

Parameters:

x : scalar or 1D array_like

x-indexes where to plot the lines.

ymin, ymax : scalar or 1D array_like

Respective beginning and end of each line. If scalars areprovided, all lines will have same length.

colors : array_like of colors, optional, default: ‘k’

linestyles : [‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’], optional

label : string, optional, default: ‘’

Returns:

lines :LineCollection

Other Parameters:
 

kwargs :LineCollection properties.

See also

hlines
horizontal lines

Examples

(Source code,png,pdf)

../_images/vline_hline_demo2.png

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘colors’, ‘x’, ‘ymax’, ‘ymin’.
matplotlib.pyplot.waitforbuttonpress(*args,**kwargs)

Blocking call to interact with the figure.

This will return True is a key was pressed, False if a mousebutton was pressed and None iftimeout was reached withouteither being pressed.

Iftimeout is negative, does not timeout.

matplotlib.pyplot.winter()

set the default colormap to winter and apply to current image if any.See help(colormaps) for more information

matplotlib.pyplot.xcorr(x,y,normed=True,detrend=<function detrend_none>,usevlines=True,maxlags=10,hold=None,data=None,**kwargs)

Plot the cross correlation betweenx andy.

The correlation with lag k is defined as sum_n x[n+k] * conj(y[n]).

Parameters:

x : sequence of scalars of length n

y : sequence of scalars of length n

hold : boolean, optional,deprecated, default: True

detrend : callable, optional, default:mlab.detrend_none

x is detrended by thedetrend callable. Default is nonormalization.

normed : boolean, optional, default: True

if True, input vectors are normalised to unit length.

usevlines : boolean, optional, default: True

if True, Axes.vlines is used to plot the vertical lines from theorigin to the acorr. Otherwise, Axes.plot is used.

maxlags : integer, optional, default: 10

number of lags to show. If None, will return all 2 * len(x) - 1lags.

Returns:

(lags, c, line, b) : where:

  • lags are a length 2`maxlags+1 lag vector.
  • c is the 2`maxlags+1 auto correlation vectorI
  • line is aLine2D instance returned byplot.
  • b is the x-axis (none, if plot is used).
Other Parameters:
 

linestyle :Line2D prop, optional, default: None

Only used if usevlines is False.

marker : string, optional, default: ‘o’

Notes

The cross correlation is performed withnumpy.correlate() withmode = 2.

Note

In addition to the above described arguments, this function can take adata keyword argument. If such adata argument is given, thefollowing arguments are replaced bydata[<arg>]:

  • All arguments with the following names: ‘x’, ‘y’.
matplotlib.pyplot.xkcd(scale=1,length=100,randomness=2)

Turns onxkcd sketch-style drawing mode.This will only have effect on things drawn after this function iscalled.

For best results, the “Humor Sans” font should be installed: it isnot included with matplotlib.

Parameters:

scale : float, optional

The amplitude of the wiggle perpendicular to the source line.

length : float, optional

The length of the wiggle along the line.

randomness : float, optional

The scale factor by which the length is shrunken or expanded.

Notes

This function works by a number of rcParams, so it will probablyoverride others you have set before.

If you want the effects of this function to be temporary, it canbe used as a context manager, for example:

withplt.xkcd():# This figure will be in XKCD-stylefig1=plt.figure()# ...# This figure will be in regular stylefig2=plt.figure()
matplotlib.pyplot.xlabel(s,*args,**kwargs)

Set thex axis label of the current axis.

Default override is:

override={'fontsize':'small','verticalalignment':'top','horizontalalignment':'center'}

See also

text()
For information on how override and the optional args work
matplotlib.pyplot.xlim(*args,**kwargs)

Get or set thex limits of the current axes.

xmin,xmax=xlim()# return the current xlimxlim((xmin,xmax))# set the xlim to xmin, xmaxxlim(xmin,xmax)# set the xlim to xmin, xmax

If you do not specify args, you can pass the xmin and xmax askwargs, e.g.:

xlim(xmax=3)# adjust the max leaving min unchangedxlim(xmin=1)# adjust the min leaving max unchanged

Setting limits turns autoscaling off for the x-axis.

The new axis limits are returned as a length 2 tuple.

matplotlib.pyplot.xscale(*args,**kwargs)

Set the scaling of thex-axis.

call signature:

xscale(scale,**kwargs)

The available scales are: ‘linear’ | ‘log’ | ‘logit’ | ‘symlog’

Different keywords may be accepted, depending on the scale:

‘linear’

‘log’

basex/basey:
The base of the logarithm
nonposx/nonposy: [‘mask’ | ‘clip’ ]
non-positive values inx ory can be masked asinvalid, or clipped to a very small positive number
subsx/subsy:

Where to place the subticks between each major tick.Should be a sequence of integers. For example, in a log10scale:[2,3,4,5,6,7,8,9]

will place 8 logarithmically spaced minor ticks betweeneach major tick.

‘logit’

nonpos: [‘mask’ | ‘clip’ ]
values beyond ]0, 1[ can be masked as invalid, or clipped to a numbervery close to 0 or 1

‘symlog’

basex/basey:
The base of the logarithm
linthreshx/linthreshy:
The range (-x,x) within which the plot is linear (toavoid having the plot go to infinity around zero).
subsx/subsy:

Where to place the subticks between each major tick.Should be a sequence of integers. For example, in a log10scale:[2,3,4,5,6,7,8,9]

will place 8 logarithmically spaced minor ticks betweeneach major tick.

linscalex/linscaley:
This allows the linear range (-linthresh tolinthresh)to be stretched relative to the logarithmic range. Itsvalue is the number of decades to use for each half of thelinear range. For example, whenlinscale == 1.0 (thedefault), the space used for the positive and negativehalves of the linear range will be equal to one decade inthe logarithmic range.
matplotlib.pyplot.xticks(*args,**kwargs)

Get or set thex-limits of the current tick locations and labels.

# return locs, labels where locs is an array of tick locations and# labels is an array of tick labels.locs,labels=xticks()# set the locations of the xticksxticks(arange(6))# set the locations and labels of the xticksxticks(arange(5),('Tom','Dick','Harry','Sally','Sue'))

The keyword args, if any, areTextproperties. For example, to rotate long labels:

xticks(arange(12),calendar.month_name[1:13],rotation=17)
matplotlib.pyplot.ylabel(s,*args,**kwargs)

Set they axis label of the current axis.

Defaults override is:

override={'fontsize':'small','verticalalignment':'center','horizontalalignment':'right','rotation'='vertical':}

See also

text()
For information on how override and the optional argswork.
matplotlib.pyplot.ylim(*args,**kwargs)

Get or set they-limits of the current axes.

ymin,ymax=ylim()# return the current ylimylim((ymin,ymax))# set the ylim to ymin, ymaxylim(ymin,ymax)# set the ylim to ymin, ymax

If you do not specify args, you can pass theymin andymax askwargs, e.g.:

ylim(ymax=3)# adjust the max leaving min unchangedylim(ymin=1)# adjust the min leaving max unchanged

Setting limits turns autoscaling off for the y-axis.

The new axis limits are returned as a length 2 tuple.

matplotlib.pyplot.yscale(*args,**kwargs)

Set the scaling of they-axis.

call signature:

yscale(scale,**kwargs)

The available scales are: ‘linear’ | ‘log’ | ‘logit’ | ‘symlog’

Different keywords may be accepted, depending on the scale:

‘linear’

‘log’

basex/basey:
The base of the logarithm
nonposx/nonposy: [‘mask’ | ‘clip’ ]
non-positive values inx ory can be masked asinvalid, or clipped to a very small positive number
subsx/subsy:

Where to place the subticks between each major tick.Should be a sequence of integers. For example, in a log10scale:[2,3,4,5,6,7,8,9]

will place 8 logarithmically spaced minor ticks betweeneach major tick.

‘logit’

nonpos: [‘mask’ | ‘clip’ ]
values beyond ]0, 1[ can be masked as invalid, or clipped to a numbervery close to 0 or 1

‘symlog’

basex/basey:
The base of the logarithm
linthreshx/linthreshy:
The range (-x,x) within which the plot is linear (toavoid having the plot go to infinity around zero).
subsx/subsy:

Where to place the subticks between each major tick.Should be a sequence of integers. For example, in a log10scale:[2,3,4,5,6,7,8,9]

will place 8 logarithmically spaced minor ticks betweeneach major tick.

linscalex/linscaley:
This allows the linear range (-linthresh tolinthresh)to be stretched relative to the logarithmic range. Itsvalue is the number of decades to use for each half of thelinear range. For example, whenlinscale == 1.0 (thedefault), the space used for the positive and negativehalves of the linear range will be equal to one decade inthe logarithmic range.
matplotlib.pyplot.yticks(*args,**kwargs)

Get or set they-limits of the current tick locations and labels.

# return locs, labels where locs is an array of tick locations and# labels is an array of tick labels.locs,labels=yticks()# set the locations of the yticksyticks(arange(6))# set the locations and labels of the yticksyticks(arange(5),('Tom','Dick','Harry','Sally','Sue'))

The keyword args, if any, areTextproperties. For example, to rotate long labels:

yticks(arange(12),calendar.month_name[1:13],rotation=45)
© Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012 - 2016 The Matplotlib development team. Last updated on May 10, 2017. Created usingSphinx 1.5.5.

[8]ページ先頭

©2009-2025 Movatter.jp