matplotlib

Table Of Contents

This Page

mplot3d API

mpl_toolkits.mplot3d.axes3d

Module containing Axes3D, an object which can plot 3D objects on a 2D matplotlib figure.

class mpl_toolkits.mplot3d.axes3d.Axes3D(fig, rect=None, *args, **kwargs)

Bases: matplotlib.axes.Axes

3D axes object.

Build an Axes3D instance in Figure fig with rect=[left, bottom, width, height] in Figure coordinates

Optional keyword arguments:

Keyword Description
azim Azimuthal viewing angle (default -60)
elev Elevation viewing angle (default 30)
add_collection3d(col, zs=0, zdir='z')

Add a 3d collection object to the plot.

2D collection types are converted to a 3D version by modifying the object and adding z coordinate information.

Supported are:
  • PolyCollection
  • LineColleciton
  • PatchCollection
bar(left, height, zs=0, zdir='z', *args, **kwargs)

Add 2D bar(s).

Argument Description
left The x coordinates of the left sides of the bars.
height The height of the bars.
zs Z coordinate of bars, if one value is specified they will all be placed at the same z.
zdir Which direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2d set.

Keyword arguments are passed onto bar().

Returns a Patch3DCollection

bar3d(x, y, z, dx, dy, dz, color='b', zsort='average', *args, **kwargs)

Generate a 3D bar, or multiple bars.

When generating multiple bars, x, y, z have to be arrays. dx, dy, dz can be arrays or scalars.

color can be:

  • A single color value, to color all bars the same color.
  • An array of colors of length N bars, to color each bar independently.
  • An array of colors of length 6, to color the faces of the bars similarly.
  • An array of colors of length 6 * N bars, to color each face independently.

When coloring the faces of the boxes specifically, this is the order of the coloring:

  1. -Z (bottom of box)
  2. +Z (top of box)
  3. -Y
  4. +Y
  5. -X
  6. +X

Keyword arguments are passed onto Poly3DCollection()

cla()
Clear axes and disable mouse button callbacks.
contour(X, Y, Z, *args, **kwargs)

Create a 3D contour plot.

Argument Description
X, Y, Data values as numpy.arrays
Z  
extend3d Whether to extend contour in 3D (default: False)
stride Stride (step size) for extending contour
zdir The direction to use: x, y or z (default)
offset If specified plot a projection of the contour lines on this position in plane normal to zdir

The positional and other keyword arguments are passed on to contour()

Returns a contour

contour3D(X, Y, Z, *args, **kwargs)

Create a 3D contour plot.

Argument Description
X, Y, Data values as numpy.arrays
Z  
extend3d Whether to extend contour in 3D (default: False)
stride Stride (step size) for extending contour
zdir The direction to use: x, y or z (default)
offset If specified plot a projection of the contour lines on this position in plane normal to zdir

The positional and other keyword arguments are passed on to contour()

Returns a contour

contourf(X, Y, Z, *args, **kwargs)

Plot filled 3D contours.

X, Y, Z: data points.

The positional and keyword arguments are passed on to contourf()

Returns a contourf

contourf3D(X, Y, Z, *args, **kwargs)

Plot filled 3D contours.

X, Y, Z: data points.

The positional and keyword arguments are passed on to contourf()

Returns a contourf

disable_mouse_rotation()
Disable mouse button callbacks.
format_coord(xd, yd)
Given the 2D view coordinates attempt to guess a 3D coordinate. Looks for the nearest edge to the point and then assumes that the point is at the same z location as the nearest point on the edge.
format_xdata(x)
Return x string formatted. This function will use the attribute self.fmt_xdata if it is callable, else will fall back on the xaxis major formatter
format_ydata(y)
Return y string formatted. This function will use the attribute self.fmt_ydata if it is callable, else will fall back on the yaxis major formatter
format_zdata(z)
Return z string formatted. This function will use the attribute self.fmt_zdata if it is callable, else will fall back on the yaxis major formatter
get_proj()

Create the projection matrix from the current viewing position.

elev stores the elevation angle in the z plane azim stores the azimuth angle in the x,y plane

dist is the distance of the eye viewing point from the object point.

get_w_lims()
Get 3d world limits.
get_xlim3d()
Get 3D x limits.
get_ylim3d()
Get 3D y limits.
get_zlim3d()
Get 3D z limits.
grid(on=True, **kwargs)
Set / unset 3D grid.
mouse_init(rotate_btn=1, zoom_btn=3)

Initializes mouse button callbacks to enable 3D rotation of the axes. Also optionally sets the mouse buttons for 3D rotation and zooming.

Argument Description
rotate_btn The integer or list of integers specifying which mouse button or buttons to use for 3D rotation of the axes. Default = 1.
zoom_btn The integer or list of integers specifying which mouse button or buttons to use to zoom the 3D axes. Default = 3.
plot(xs, ys, *args, **kwargs)

Plot 2D or 3D data.

Argument Description
xs, ys X, y coordinates of vertices
zs z value(s), either one for all points or one for each point.
zdir Which direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2d set.

Other arguments are passed on to plot()

plot3D(xs, ys, *args, **kwargs)

Plot 2D or 3D data.

Argument Description
xs, ys X, y coordinates of vertices
zs z value(s), either one for all points or one for each point.
zdir Which direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2d set.

Other arguments are passed on to plot()

plot_surface(X, Y, Z, *args, **kwargs)

Create a surface plot.

By default it will be colored in shades of a solid color, but it also supports color mapping by supplying the cmap argument.

Argument Description
X, Y, Z Data values as numpy.arrays
rstride Array row stride (step size)
cstride Array column stride (step size)
color Color of the surface patches
cmap A colormap for the surface patches.
facecolors Face colors for the individual patches
norm An instance of Normalize to map values to colors
vmin Minimum value to map
vmax Maximum value to map
shade Whether to shade the facecolors

Other arguments are passed on to __init__()

plot_wireframe(X, Y, Z, *args, **kwargs)

Plot a 3D wireframe.

Argument Description
X, Y, Data values as numpy.arrays
Z  
rstride Array row stride (step size)
cstride Array column stride (step size)

Keyword arguments are passed on to matplotlib.collections.LineCollection.__init__().

Returns a Line3DCollection

scatter(xs, ys, zs=0, zdir='z', *args, **kwargs)

Create a scatter plot.

Argument Description
xs, ys Positions of data points.
zs Either an array of the same length as xs and ys or a single value to place all points in the same plane. Default is 0.
zdir Which direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2d set.

Keyword arguments are passed on to scatter().

Returns a Patch3DCollection

scatter3D(xs, ys, zs=0, zdir='z', *args, **kwargs)

Create a scatter plot.

Argument Description
xs, ys Positions of data points.
zs Either an array of the same length as xs and ys or a single value to place all points in the same plane. Default is 0.
zdir Which direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2d set.

Keyword arguments are passed on to scatter().

Returns a Patch3DCollection

set_xlabel(xlabel, fontdict=None, **kwargs)
Set xlabel.
set_xlim3d(*args, **kwargs)
Set 3D x limits.
set_ylabel(ylabel, fontdict=None, **kwargs)
Set ylabel.
set_ylim3d(*args, **kwargs)
Set 3D y limits.
set_zlabel(zlabel, fontdict=None, **kwargs)
Set zlabel.
set_zlim3d(*args, **kwargs)
Set 3D z limits.
text(x, y, z, s, zdir=None, **kwargs)
Add text to the plot. kwargs will be passed on to Axes.text, except for the zdir keyword, which sets the direction to be used as the z direction.
text2D(x, y, s, fontdict=None, withdash=False, **kwargs)

call signature:

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

Add text in string s to axis at location x, y, data coordinates.

Keyword arguments:

fontdict:
A dictionary to override the default text properties. If fontdict is None, the defaults are determined by your rc parameters.
withdash: [ False | True ]
Creates a TextWithDash instance instead of a Text instance.

Individual keyword arguments can be used to override any given parameter:

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 is lower-left and 1,1 is upper-right). The example below places text 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 (eg. to set a background color) by using the keyword bbox. bbox is a dictionary of matplotlib.patches.Rectangle properties. For example:

text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))

Valid kwargs are matplotlib.text.Text properties:

Property Description
agg_filter unknown
alpha float (0.0 transparent through 1.0 opaque)
animated [True | False]
axes an Axes instance
backgroundcolor any matplotlib color
bbox rectangle prop dict
clip_box a matplotlib.transforms.Bbox instance
clip_on [True | False]
clip_path [ (Path, Transform) | Patch | None ]
color any matplotlib color
contains a callable function
family or fontfamily or fontname or name [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ]
figure a matplotlib.figure.Figure instance
fontproperties or font_properties a matplotlib.font_manager.FontProperties instance
gid an id string
horizontalalignment or ha [ ‘center’ | ‘right’ | ‘left’ ]
label any string
linespacing float (multiple of font size)
lod [True | False]
multialignment [‘left’ | ‘right’ | ‘center’ ]
path_effects unknown
picker [None|float|boolean|callable]
position (x,y)
rasterized [True | False | None]
rotation [ angle in degrees | ‘vertical’ | ‘horizontal’ ]
rotation_mode unknown
size or fontsize [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’ ]
snap unknown
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’]
text string or anything printable with ‘%s’ conversion.
transform Transform instance
url a url string
variant or fontvariant [ ‘normal’ | ‘small-caps’ ]
verticalalignment or va or ma [ ‘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’ ]
x float
y float
zorder any number
text3D(x, y, z, s, zdir=None, **kwargs)
Add text to the plot. kwargs will be passed on to Axes.text, except for the zdir keyword, which sets the direction to be used as the z direction.
view_init(elev=None, azim=None)

Set the elevation and azimuth of the axes.

This can be used to rotate the axes programatically.

‘elev’ stores the elevation angle in the z plane. ‘azim’ stores the azimuth angle in the x,y plane.

if elev or azim are None (default), then the initial value is used which was specified in the Axes3D constructor.

mpl_toolkits.mplot3d.axes3d.get_test_data(delta=0.05)
Return a tuple X, Y, Z with a test data set.
mpl_toolkits.mplot3d.axes3d.sensible_format_data(self, value)
Used to generate more comprehensible numbers in status bar

mpl_toolkits.mplot3d.art3d

Module containing 3D artist code and functions to convert 2D artists into 3D versions which can be added to an Axes3D.

class mpl_toolkits.mplot3d.art3d.Line3D(xs, ys, zs, *args, **kwargs)

Bases: matplotlib.lines.Line2D

3D line object.

Keyword arguments are passed onto Line2D().

class mpl_toolkits.mplot3d.art3d.Line3DCollection(segments, *args, **kwargs)

Bases: matplotlib.collections.LineCollection

A collection of 3D lines.

Keyword arguments are passed onto LineCollection().

do_3d_projection(renderer)
Project the points according to renderer matrix.
set_segments(segments)
Set 3D segments
class mpl_toolkits.mplot3d.art3d.Patch3D(*args, **kwargs)

Bases: matplotlib.patches.Patch

3D patch object.

class mpl_toolkits.mplot3d.art3d.Patch3DCollection(*args, **kwargs)

Bases: matplotlib.collections.PatchCollection

A collection of 3D patches.

class mpl_toolkits.mplot3d.art3d.PathPatch3D(path, **kwargs)

Bases: mpl_toolkits.mplot3d.art3d.Patch3D

3D PathPatch object.

class mpl_toolkits.mplot3d.art3d.Poly3DCollection(verts, *args, **kwargs)

Bases: matplotlib.collections.PolyCollection

A collection of 3D polygons.

Create a Poly3DCollection.

verts should contain 3D coordinates.

Keyword arguments: zsort, see set_zsort for options.

Note that this class does a bit of magic with the _facecolors and _edgecolors properties.

do_3d_projection(renderer)
Perform the 3D projection for this object.
get_vector(segments3d)
Optimize points for projection
set_sort_zpos(val)
Set the position to use for z-sorting.
set_verts(verts, closed=True)
Set 3D vertices.
set_zsort(zsort)
Set z-sorting behaviour:
boolean: if True use default ‘average’ string: ‘average’, ‘min’ or ‘max’
class mpl_toolkits.mplot3d.art3d.Text3D(x=0, y=0, z=0, text='', zdir='z', **kwargs)

Bases: matplotlib.text.Text

Text object with 3D position and (in the future) direction.

x, y, z Position of text text Text string to display zdir Direction of text

Keyword arguments are passed onto Text().

mpl_toolkits.mplot3d.art3d.get_colors(c, num)
Stretch the color argument to provide the required number num
mpl_toolkits.mplot3d.art3d.get_patch_verts(patch)
Return a list of vertices for the path of a patch.
mpl_toolkits.mplot3d.art3d.juggle_axes(xs, ys, zs, zdir)
Reorder coordinates so that 2D xs, ys can be plotted in the plane orthogonal to zdir. zdir is normally x, y or z. However, if zdir starts with a ‘-‘ it is interpreted as a compensation for rotate_axes.
mpl_toolkits.mplot3d.art3d.line_2d_to_3d(line, zs=0, zdir='z')
Convert a 2D line to 3D.
mpl_toolkits.mplot3d.art3d.line_collection_2d_to_3d(col, zs=0, zdir='z')
Convert a LineCollection to a Line3DCollection object.
mpl_toolkits.mplot3d.art3d.norm_angle(a)
Return angle between -180 and +180
mpl_toolkits.mplot3d.art3d.norm_text_angle(a)
Return angle between -90 and +90
mpl_toolkits.mplot3d.art3d.patch_2d_to_3d(patch, z=0, zdir='z')
Convert a Patch to a Patch3D object.
mpl_toolkits.mplot3d.art3d.patch_collection_2d_to_3d(col, zs=0, zdir='z')
Convert a PatchCollection to a Patch3DCollection object.
mpl_toolkits.mplot3d.art3d.path_to_3d_segment(path, zs=0, zdir='z')
Convert a path to a 3D segment.
mpl_toolkits.mplot3d.art3d.pathpatch_2d_to_3d(pathpatch, z=0, zdir='z')
Convert a PathPatch to a PathPatch3D object.
mpl_toolkits.mplot3d.art3d.paths_to_3d_segments(paths, zs=0, zdir='z')
Convert paths from a collection object to 3D segments.
mpl_toolkits.mplot3d.art3d.poly_collection_2d_to_3d(col, zs=0, zdir='z')
Convert a PolyCollection to a Poly3DCollection object.
mpl_toolkits.mplot3d.art3d.rotate_axes(xs, ys, zs, zdir)
Reorder coordinates so that the axes are rotated with zdir along the original z axis. Prepending the axis with a ‘-‘ does the inverse transform, so zdir can be x, -x, y, -y, z or -z
mpl_toolkits.mplot3d.art3d.text_2d_to_3d(obj, z=0, zdir='z')
Convert a Text to a Text3D object.
mpl_toolkits.mplot3d.art3d.zalpha(colors, zs)
Modify the alphas of the color list according to depth

mpl_toolkits.mplot3d.proj3d

Various transforms used for by the 3D code

mpl_toolkits.mplot3d.proj3d.line2d(p0, p1)
Return 2D equation of line in the form ax+by+c = 0
mpl_toolkits.mplot3d.proj3d.line2d_dist(l, p)
Distance from line to point line is a tuple of coefficients a,b,c
mpl_toolkits.mplot3d.proj3d.line2d_seg_dist(p1, p2, p0)

distance(s) from line defined by p1 - p2 to point(s) p0

p0[0] = x(s) p0[1] = y(s)

intersection point p = p1 + u*(p2-p1) and intersection point lies within segement if u is between 0 and 1

mpl_toolkits.mplot3d.proj3d.mod(v)
3d vector length
mpl_toolkits.mplot3d.proj3d.proj_transform(xs, ys, zs, M)
Transform the points by the projection matrix
mpl_toolkits.mplot3d.proj3d.proj_transform_clip(xs, ys, zs, M)
Transform the points by the projection matrix and return the clipping result returns txs,tys,tzs,tis
mpl_toolkits.mplot3d.proj3d.transform(xs, ys, zs, M)
Transform the points by the projection matrix