The plotting module allows you to make 2-dimensional and 3-dimensional plots. Presently the plots are rendered using matplotlib as a backend. It is also possible to plot 2-dimensional plots using a TextBackend if you don’t have matplotlib.
The plotting module has the following functions:
The above functions are only for convenience and ease of use. It is possible to plot any plot by passing the corresponding Series class to Plot as argument.
The central class of the plotting module.
For interactive work the function plot is better suited.
This class permits the plotting of sympy expressions using numerous backends (matplotlib, textplot, the old pyglet module for sympy, Google charts api, etc).
The figure can contain an arbitrary number of plots of sympy expressions, lists of coordinates of points, etc. Plot has a private attribute _series that contains all data series to be plotted (expressions for lines or surfaces, lists of points, etc (all subclasses of BaseSeries)). Those data series are instances of classes not imported by from sympy import *.
The customization of the figure is on two levels. Global options that concern the figure as a whole (eg title, xlabel, scale, etc) and per-data series options (eg name) and aesthetics (eg. color, point shape, line type, etc.).
The difference between options and aesthetics is that an aesthetic can be a function of the coordinates (or parameters in a parametric plot). The supported values for an aesthetic are: - None (the backend uses default values) - a constant - a function of one variable (the first coordinate or parameter) - a function of two variables (the first and second coordinate or parameters) - a function of three variables (only in nonparametric 3D plots) Their implementation depends on the backend so they may not work in some backends.
If the plot is parametric and the arity of the aesthetic function permits it the aesthetic is calculated over parameters and not over coordinates. If the arity does not permit calculation over parameters the calculation is done over coordinates.
Only cartesian coordinates are supported for the moment, but you can use the parametric plots to plot in polar, spherical and cylindrical coordinates.
The arguments for the constructor Plot must be subclasses of BaseSeries.
Any global option can be specified as a keyword argument.
The global options for a figure are:
The per data series options and aesthetics are: There are none in the base series. See below for options for subclasses.
Some data series support additional aesthetics or options:
ListSeries, LineOver1DRangeSeries, Parametric2DLineSeries, Parametric3DLineSeries support the following:
Aesthetics:
options:
SurfaceOver2DRangeSeries, ParametricSurfaceSeries support the following:
aesthetics:
Plots a function of a single variable.
The plotting uses an adaptive algorithm which samples recursively to accurately plot the plot. The adaptive algorithm uses a random point near the midpoint of two points that has to be further sampled. Hence the same plots can appear slightly different.
See also
Plot, LineOver1DRangeSeries.
Examples
>>> from sympy import symbols
>>> from sympy.plotting import plot
>>> x = symbols('x')
Single Plot
>>> plot(x**2, (x, -5, 5))
Plot object containing:
[0]: cartesian line: x**2 for x over (-5.0, 5.0)
Multiple plots with single range.
>>> plot(x, x**2, x**3, (x, -5, 5))
Plot object containing:
[0]: cartesian line: x for x over (-5.0, 5.0)
[1]: cartesian line: x**2 for x over (-5.0, 5.0)
[2]: cartesian line: x**3 for x over (-5.0, 5.0)
Multiple plots with different ranges.
>>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
Plot object containing:
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
[1]: cartesian line: x for x over (-5.0, 5.0)
No adaptive sampling.
>>> plot(x**2, adaptive=False, nb_of_points=400)
Plot object containing:
[0]: cartesian line: x**2 for x over (-10.0, 10.0)
Usage
Single Plot
plot(expr, range, **kwargs)
If the range is not specified, then a default range of (-10, 10) is used.
Multiple plots with same range.
plot(expr1, expr2, ..., range, **kwargs)
If the range is not specified, then a default range of (-10, 10) is used.
Multiple plots with different ranges.
plot((expr1, range), (expr2, range), ..., **kwargs)
Range has to be specified for every expression.
Default range may change in the future if a more advanced default range detection algorithm is implemented.
Arguments
expr : Expression representing the function of single variable
range: (x, 0, 5), A 3-tuple denoting the range of the free variable.
Keyword Arguments
Arguments for LineOver1DRangeSeries class:
adaptive: Boolean. The default value is set to True. Set adaptive to False and specify nb_of_points if uniform sampling is required.
depth: int Recursion depth of the adaptive algorithm. A depth of value n samples a maximum of \(2^{n}\) points.
nb_of_points: int. Used when the adaptive is set to False. The function is uniformly sampled at nb_of_points number of points.
Aesthetics options:
line_color: float. Specifies the color for the plot. See Plot to see how to set color for the plots.
If there are multiple plots, then the same series series are applied to all the plots. If you want to set these options separately, you can index the Plot object returned and set it.
Arguments for Plot class:
title : str. Title of the plot. It is set to the latex representation of the expression, if the plot has only one expression.
xlabel : str. Label for the x - axis.
ylabel : str. Label for the y - axis.
xscale: {‘linear’, ‘log’} Sets the scaling of the x - axis.
yscale: {‘linear’, ‘log’} Sets the scaling if the y - axis.
axis_center: tuple of two floats denoting the coordinates of the center or {‘center’, ‘auto’}
xlim : tuple of two floats, denoting the x - axis limits.
ylim : tuple of two floats, denoting the y - axis limits.
Plots a 2D parametric plot.
The plotting uses an adaptive algorithm which samples recursively to accurately plot the plot. The adaptive algorithm uses a random point near the midpoint of two points that has to be further sampled. Hence the same plots can appear slightly different.
See also
Examples
>>> from sympy import symbols, cos, sin
>>> from sympy.plotting import plot_parametric
>>> u = symbols('u')
Single Parametric plot
>>> plot_parametric(cos(u), sin(u), (u, -5, 5))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
Multiple parametric plot with single range.
>>> plot_parametric((cos(u), sin(u)), (u, cos(u)))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0)
[1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0)
Multiple parametric plots.
>>> plot_parametric((cos(u), sin(u), (u, -5, 5)),
... (cos(u), u, (u, -5, 5)))
Plot object containing:
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
[1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0)
Usage
Single plot.
plot_parametric(expr_x, expr_y, range, **kwargs)
If the range is not specified, then a default range of (-10, 10) is used.
Multiple plots with same range.
plot_parametric((expr1_x, expr1_y), (expr2_x, expr2_y), range, **kwargs)
If the range is not specified, then a default range of (-10, 10) is used.
Multiple plots with different ranges.
plot_parametric((expr_x, expr_y, range), ..., **kwargs)
Range has to be specified for every expression.
Default range may change in the future if a more advanced default range detection algorithm is implemented.
Arguments
expr_x : Expression representing the function along x.
expr_y : Expression representing the function along y.
range: (u, 0, 5), A 3-tuple denoting the range of the parameter variable.
Keyword Arguments
Arguments for Parametric2DLineSeries class:
adaptive: Boolean. The default value is set to True. Set adaptive to False and specify nb_of_points if uniform sampling is required.
depth: int Recursion depth of the adaptive algorithm. A depth of value n samples a maximum of \(2^{n}\) points.
nb_of_points: int. Used when the adaptive is set to False. The function is uniformly sampled at nb_of_points number of points.
Aesthetics
line_color: function which returns a float. Specifies the color for the plot. See sympy.plotting.Plot for more details.
If there are multiple plots, then the same Series arguments are applied to all the plots. If you want to set these options separately, you can index the returned Plot object and set it.
Arguments for Plot class:
xlabel : str. Label for the x - axis.
ylabel : str. Label for the y - axis.
xscale: {‘linear’, ‘log’} Sets the scaling of the x - axis.
yscale: {‘linear’, ‘log’} Sets the scaling if the y - axis.
axis_center: tuple of two floats denoting the coordinates of the center or {‘center’, ‘auto’}
xlim : tuple of two floats, denoting the x - axis limits.
ylim : tuple of two floats, denoting the y - axis limits.
Plots a 3D surface plot.
See also
Examples
>>> from sympy import symbols
>>> from sympy.plotting import plot3d
>>> x, y = symbols('x y')
Single plot
>>> plot3d(x*y, (x, -5, 5), (y, -5, 5))
Plot object containing:
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
Multiple plots with same range
>>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
Plot object containing:
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
[1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
Multiple plots with different ranges.
>>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)),
... (x*y, (x, -3, 3), (y, -3, 3)))
Plot object containing:
[0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0)
[1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0)
Usage
Single plot
plot3d(expr, range_x, range_y, **kwargs)
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plot with the same range.
plot3d(expr1, expr2, range_x, range_y, **kwargs)
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plots with different ranges.
plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range detection algorithm is implemented.
Arguments
expr : Expression representing the function along x.
range_x: (x, 0, 5), A 3-tuple denoting the range of the x variable.
Keyword Arguments
Arguments for SurfaceOver2DRangeSeries class:
nb_of_points_x: int. The x range is sampled uniformly at nb_of_points_x of points.
nb_of_points_y: int. The y range is sampled uniformly at nb_of_points_y of points.
Aesthetics:
surface_color: Function which returns a float. Specifies the color for the surface of the plot. See sympy.plotting.Plot for more details.
If there are multiple plots, then the same series arguments are applied to all the plots. If you want to set these options separately, you can index the returned Plot object and set it.
Arguments for Plot class:
title : str. Title of the plot.
Plots a 3D parametric line plot.
See also
Examples
>>> from sympy import symbols, cos, sin
>>> from sympy.plotting import plot3d_parametric_line
>>> u = symbols('u')
Single plot.
>>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5))
Plot object containing:
[0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
Multiple plots.
>>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)),
... (sin(u), u**2, u, (u, -5, 5)))
Plot object containing:
[0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
[1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0)
Usage
Single plot:
plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)
If the range is not specified, then a default range of (-10, 10) is used.
Multiple plots.
plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range detection algorithm is implemented.
Arguments
expr_x : Expression representing the function along x.
expr_y : Expression representing the function along y.
expr_z : Expression representing the function along z.
range: (u, 0, 5), A 3-tuple denoting the range of the parameter variable.
Keyword Arguments
Arguments for Parametric3DLineSeries class.
nb_of_points: The range is uniformly sampled at nb_of_points number of points.
Aesthetics:
line_color: function which returns a float. Specifies the color for the plot. See sympy.plotting.Plot for more details.
If there are multiple plots, then the same series arguments are applied to all the plots. If you want to set these options separately, you can index the returned Plot object and set it.
Arguments for Plot class.
title : str. Title of the plot.
Plots a 3D parametric surface plot.
See also
Examples
>>> from sympy import symbols, cos, sin
>>> from sympy.plotting import plot3d_parametric_surface
>>> u, v = symbols('u v')
Single plot.
>>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v,
... (u, -5, 5), (v, -5, 5))
Plot object containing:
[0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0)
Usage
Single plot.
plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)
If the ranges is not specified, then a default range of (-10, 10) is used.
Multiple plots.
plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)
Ranges have to be specified for every expression.
Default range may change in the future if a more advanced default range detection algorithm is implemented.
Arguments
expr_x: Expression representing the function along x.
expr_y: Expression representing the function along y.
expr_z: Expression representing the function along z.
range_u: (u, 0, 5), A 3-tuple denoting the range of the u variable.
range_v: (v, 0, 5), A 3-tuple denoting the range of the v variable.
Keyword Arguments
Arguments for ParametricSurfaceSeries class:
nb_of_points_u: int. The u range is sampled uniformly at nb_of_points_v of points
nb_of_points_y: int. The v range is sampled uniformly at nb_of_points_y of points
Aesthetics:
surface_color: Function which returns a float. Specifies the color for the surface of the plot. See sympy.plotting.Plot for more details.
If there are multiple plots, then the same series arguments are applied for all the plots. If you want to set these options separately, you can index the returned Plot object and set it.
Arguments for Plot class:
title : str. Title of the plot.
A plot function to plot implicit equations / inequalities.
Arguments
The following arguments can be passed as named parameters.
set to False if you want to use a mesh grid.
Default value is 0. Takes value in the range (0, 4).
used. Default value is 200.
title string .The title for the plot.
xlabel string. The label for the x - axis
ylabel string. The label for the y - axis
plot_implicit, by default, uses interval arithmetic to plot functions. If the expression cannot be plotted using interval arithmetic, it defaults to a generating a contour using a mesh grid of fixed number of points. By setting adaptive to False, you can force plot_implicit to use the mesh grid. The mesh grid method can be effective when adaptive plotting using interval arithmetic, fails to plot with small line width.
Examples:
Plot expressions:
>>> from sympy import plot_implicit, cos, sin, symbols, Eq, And
>>> x, y = symbols('x y')
Without any ranges for the symbols in the expression
>>> p1 = plot_implicit(Eq(x**2 + y**2, 5))
With the range for the symbols
>>> p2 = plot_implicit(Eq(x**2 + y**2, 3),
... (x, -3, 3), (y, -3, 3))
With depth of recursion as argument.
>>> p3 = plot_implicit(Eq(x**2 + y**2, 5),
... (x, -4, 4), (y, -4, 4), depth = 2)
Using mesh grid and not using adaptive meshing.
>>> p4 = plot_implicit(Eq(x**2 + y**2, 5),
... (x, -5, 5), (y, -2, 2), adaptive=False)
Using mesh grid with number of points as input.
>>> p5 = plot_implicit(Eq(x**2 + y**2, 5),
... (x, -5, 5), (y, -2, 2),
... adaptive=False, points=400)
Plotting regions.
>>> p6 = plot_implicit(y > x**2)
Plotting Using boolean conjunctions.
>>> p7 = plot_implicit(And(y > x, y > -x))
Base class for the data objects containing stuff to be plotted.
The backend should check if it supports the data series that it’s given. (eg TextBackend supports only LineOver1DRange). It’s the backend responsibility to know how to use the class of data series that it’s given.
Some data series classes are grouped (using a class attribute like is_2Dline) according to the api they present (based only on convention). The backend is not obliged to use that api (eg. The LineOver1DRange belongs to the is_2Dline group and presents the get_points method, but the TextBackend does not use the get_points method).
A base class for 2D lines.
Representation for a line consisting of a sympy expression over a range.
Adaptively gets segments for plotting.
The adaptive sampling is done by recursively checking if three points are almost collinear. If they are not collinear, then more points are added between those points.
References
Representation for a line consisting of two parametric sympy expressions over a range.
Adaptively gets segments for plotting.
The adaptive sampling is done by recursively checking if three points are almost collinear. If they are not collinear, then more points are added between those points.
References
A base class for 3D lines.
Most of the stuff is derived from Line2DBaseSeries.
Representation for a 3D line consisting of two parametric sympy expressions and a range.
Representation for a 3D surface consisting of a sympy expression and 2D range.
This is the documentation for the old plotting module that uses pyglet. This module has some limitations and is not actively developed anymore. For an alternative you can look at the new plotting module.
The pyglet plotting module can do nice 2D and 3D plots that can be controlled by console commands as well as keyboard and mouse, with the only dependency being pyglet.
Here is the simplest usage:
>>> from sympy import var, Plot
>>> var('x y z')
>>> Plot(x*y**3-y*x**3)
To see lots of plotting examples, see examples/pyglet_plotting.py and try running it in interactive mode (python -i plotting.py):
$ python -i examples/pyglet_plotting.py
And type for instance example(7) or example(11).
See also the Plotting Module wiki page for screenshots.
Camera | Keys |
---|---|
Sensitivity Modifier | SHIFT |
Zoom | R and F, Page Up and Down, Numpad + and - |
Rotate View X,Y axis | Arrow Keys, A,S,D,W, Numpad 4,6,8,2 |
Rotate View Z axis | Q and E, Numpad 7 and 9 |
Rotate Ordinate Z axis | Z and C, Numpad 1 and 3 |
View XY | F1 |
View XZ | F2 |
View YZ | F3 |
View Perspective | F4 |
Reset | X, Numpad 5 |
Axes | Keys |
---|---|
Toggle Visible | F5 |
Toggle Colors | F6 |
Window | Keys |
---|---|
Close | ESCAPE |
Screenshot | F8 |
The mouse can be used to rotate, zoom, and translate by dragging the left, middle, and right mouse buttons respectively.
Plot supports several curvilinear coordinate modes, and they are independent for each plotted function. You can specify a coordinate mode explicitly with the ‘mode’ named argument, but it can be automatically determined for cartesian or parametric plots, and therefore must only be specified for polar, cylindrical, and spherical modes.
Specifically, Plot(function arguments) and Plot.__setitem__(i, function arguments) (accessed using array-index syntax on the Plot instance) will interpret your arguments as a cartesian plot if you provide one function and a parametric plot if you provide two or three functions. Similarly, the arguments will be interpreted as a curve is one variable is used, and a surface if two are used.
Supported mode names by number of variables:
>>> Plot(1, 'mode=spherical; color=zfade4')
Note that function parameters are given as option strings of the form “key1=value1; key2 = value2” (spaces are truncated). Keyword arguments given directly to plot apply to the plot itself.
The basic format for variable intervals is [var, min, max, steps]. However, the syntax is quite flexible, and arguments not specified are taken from the defaults for the current coordinate mode:
>>> Plot(x**2) # implies [x,-5,5,100]
>>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40]
>>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100]
>>> Plot(x**2, [x,-13,13,100])
>>> Plot(x**2, [-13,13]) # [x,-13,13,100]
>>> Plot(x**2, [x,-13,13]) # [x,-13,13,100]
>>> Plot(1*x, [], [x], 'mode=cylindrical') # [unbound_theta,0,2*Pi,40], [x,-1,1,20]
>>> p = Plot(visible=False)
>>> f = x**2
>>> p[1] = f
>>> p[2] = f.diff(x)
>>> p[3] = f.diff(x).diff(x)
>>> p
[1]: x**2, 'mode=cartesian'
[2]: 2*x, 'mode=cartesian'
[3]: 2, 'mode=cartesian'
>>> p.show()
>>> p.clear()
>>> p
<blank plot>
>>> p[1] = x**2+y**2
>>> p[1].style = 'solid'
>>> p[2] = -x**2-y**2
>>> p[2].style = 'wireframe'
>>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
>>> p[1].style = 'both'
>>> p[2].style = 'both'
>>> p.close()
The following code plots a saddle and color it by the magnitude of its gradient:
>>> fz = x**2-y**2
>>> Fx, Fy, Fz = fz.diff(x), fz.diff(y), 0
>>> p[1] = fz, 'style=solid'
>>> p[1].color = (Fx**2 + Fy**2 + Fz**2)**(0.5)
The coloring algorithm works like this:
When not specified explicitly, the default color gradient is f(0.0)=(0.4,0.4,0.4) -> f(1.0)=(0.9,0.9,0.9). In our case, everything is gray-scale because we have applied the default color gradient uniformly for each color component. When defining a color scheme in this way, you might want to supply a color gradient as well:
>>> p[1].color = (Fx**2 + Fy**2 + Fz**2)**(0.5), (0.1,0.1,0.9), (0.9,0.1,0.1)
Here’s a color gradient with four steps:
>>> gradient = [ 0.0, (0.1,0.1,0.9), 0.3, (0.1,0.9,0.1),
... 0.7, (0.9,0.9,0.1), 1.0, (1.0,0.0,0.0) ]
>>> p[1].color = (Fx**2 + Fy**2 + Fz**2)**(0.5), gradient
The other way to specify a color scheme is to give a separate function for each component r, g, b. With this syntax, the default color scheme is defined:
>>> p[1].color = z,y,x, (0.4,0.4,0.4), (0.9,0.9,0.9)
This maps z->red, y->green, and x->blue. In some cases, you might prefer to use the following alternative syntax:
>>> p[1].color = z,(0.4,0.9), y,(0.4,0.9), x,(0.4,0.9)
You can still use multi-step gradients with three-function color schemes.
The plotting module is capable of plotting some 2D geometric entities like line, circle and ellipse. The following example plots a circle and a tangent line at a random point on the ellipse.
In [1]: p = Plot(axes='label_axes=True')
In [2]: c = Circle(Point(0,0), 1)
In [3]: t = c.tangent_line(c.random_point())
In [4]: p[0] = c
In [5]: p[1] = t
Plotting polygons (Polygon, RegularPolygon, Triangle) are not supported directly. However a polygon can be plotted through a loop as follows.
In [6]: p = Plot(axes='label_axes=True')
In [7]: t = RegularPolygon(Point(0,0), 1, 5)
In [8]: for i in range(len(t.sides)):
....: p[i] = t.sides[i]