3D general plotting

NOTE: For technical reasons, all interactive-widgets plots in this documentation are created using Holoviz’s Panel. Often, they will ran just fine with ipywidgets too. However, if a specific example uses the param library, or widgets from the panel module, then users will have to modify the params dictionary in order to make it work with ipywidgets. Refer to Interactive module for more information.

spb.plot_functions.functions_3d.plot3d(*args, **kwargs)[source]

Plots a 3D surface plot.

Typical usage examples are in the followings:

  • Plotting a single expression:

    plot3d(expr, range_x, range_y, **kwargs)
    
  • Plotting multiple expressions with the same ranges:

    plot3d(expr1, expr2, range_x, range_y, **kwargs)
    
  • Plotting multiple expressions with different ranges, custom labels and rendering options:

    plot3d(
       (expr1, range_x1, range_y1, label1 [opt], rendering_kw1 [opt]),
       (expr2, range_x2, range_y2, label2 [opt], rendering_kw2 [opt]),
       ..., **kwargs)
    

Note: it is important to specify at least the range_x, otherwise the function might create a rotated plot.

Parameters:
expr

The expression representing the function of two variables to be plotted. It can be a:

  • Symbolic expression.

  • Numerical function of two variable, supporting vectorization. In this case the following keyword arguments are not supported: params.

range_xtuple, Tuple

A 3-tuple (symb, min, max) denoting the range of the x variable. Default values: min=-10 and max=10.

range_ytuple, Tuple

A 3-tuple (symb, min, max) denoting the range of the y variable. Default values: min=-10 and max=10.

labelstr

Set the label associated to this series, which will be eventually shown on the legend or colorbar.

aspectstr, tuple, list, dict

Set the aspect ratio.

Possible values for Matplotlib (only works for a 2D plot):

  • "auto": Matplotlib will fit the plot in the vibile area.

  • "equal": sets equal spacing.

  • tuple containing 2 float numbers, from which the aspect ratio is computed. This only works for 2D plots.

Possible values for Plotly:

  • "equal": sets equal spacing on the axis of a 2D plot.

  • For 3D plots:

    • "cube": fix the ratio to be a cube

    • "data": draw axes in proportion of their ranges

    • "auto": automatically produce something that is well proportioned using ‘data’ as the default.

    • manually set the aspect ratio by providing a dictionary. For example: dict(x=1, y=1, z=2) forces the z-axis to appear twice as big as the other two.

Possible values for Bokeh:

  • "equal": sets equal spacing.

ax

An existing Matplotlib’s Axes over which the symbolic expressions will be plotted.

axisbool

Show the axis in the figure. Default value: True.

axis_centerstr, tuple

Set the location of the intersection between the horizontal and vertical axis in a 2D plot. It only works with Matplotlib and it can receive the following values:

  • None: traditional layout, with the horizontal axis fixed on the bottom and the vertical axis fixed on the left. This is the default value.

  • a tuple (x, y) specifying the exact intersection point.

  • 'center': center of the current plot area.

  • 'auto': the intersection point is automatically computed.

camera

Set the camera position for 3D plots.

For Matplotlib, it can be a dictionary of keyword arguments that will be passed to the Axes3D.view_init method. Refer to the following link for more information: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html#mpl_toolkits.mplot3d.axes3d.Axes3D.view_init

For Plotly, it can be a dictionary of keyword arguments that will be passed to the layout’s scene_camera. Refer to the following link for more information: https://plotly.com/python/3d-camera-controls/

For K3D-Jupyter, it is list of 9 numbers, namely:

  • x_cam, y_cam, z_cam: the position of the camera in the scene

  • x_tar, y_tar, z_tar: the position of the target of the camera

  • x_up, y_up, z_up: components of the up vector

color_func

Define a custom color mapping. It can either be:

  • A numerical function supporting vectorization. The arity can be:

    • 2 arguments: f(x, y) where x, y are the coordinates of the points.

    • 3 arguments: f(x, y, z) where x, y, z are the coordinates of the points.

  • A symbolic expression having at most as many free symbols as expr.

  • None: the default value (color mapping according to the z coordinate).

colorbarbool

Toggle the visibility of the colorbar associated to the current data series. Note that a colorbar is only visible if use_cm=True and color_func is not None. Default value: True.

colorbar_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values on the colorbar at each multiple of a specified quantity. This only works when use_cm=True.

colorlooplist, tuple

List of colors to be used in line plots or solid color surfaces.

colormapslist, tuple

List of color maps to render surfaces.

cyclic_colormapslist, tuple

List of cyclic color maps to render complex series (the phase/argument ranges over [-pi, pi]).

fig

Get or set the figure where to plot into.

force_real_evalbool

By default, numerical evaluation is performed over complex numbers, which is slower but produces correct results. However, when the symbolic expression is converted to a numerical function with lambdify, the resulting function may not like to be evaluated over complex numbers. In such cases, forcing the evaluation to be performed over real numbers might be a good choice. The plotting module should be able to detect such occurences and automatically activate this option. If that is not the case, or evaluation performance is of paramount importance, set this parameter to True, but be aware that it might produce wrong results. Default value: False.

gridbool, dict

Toggle the visibility of major grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

hookslist

List of functions expecting one argument, the current plot object, which allows users to further customize the appearance of the plot before it is shown on the screen. The hooks are executed:

  1. after the figure has been initialized and populated with numerical data.

  2. after the existing renderers update the visualization because the user interacted with some widget.

Note: let p be the plot object. Then, the user can access the figure with p.fig. In case of spb.backends.matplotlib.MatplotlibBackend, the user can also retrieve the axes in which data was added with p.ax.

is_polarbool

If True, requests a polar discretization. In this case, range_x represents the radius, while range_y represents the angle. Default value: False.

legendbool

Toggle the visibility of the legend. If None, the backend will automatically determine if it is appropriate to show it. Default value: None.

minor_gridbool, dict

Toggle the visibility of minor grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

modules

Specify the evaluation modules to be used by lambdify. If not specified, the evaluation will be done with NumPy/SciPy.

n1int

Number of discretization points along the x-axis to be used in the evaluation. Related parameters: xscale. It must be: 2 ≤ n1 < ∞. Default value: 100.

n2int

Number of discretization points along the y-axis to be used in the evaluation. Related parameters: yscale. It must be: 2 ≤ n2 < ∞. Default value: 100.

only_integersbool

Discretize the domain using only integer numbers. When this parameter is True, the number of discretization points is choosen by the algorithm. Default value: False.

paramsdict, optional

A dictionary mapping symbols to parameters. If provided, this dictionary enables the interactive-widgets plot.

When calling a plotting function, the parameter can be specified with:

  • a widget from the ipywidgets module.

  • a widget from the panel module.

  • a tuple of the form:

    (default, min, max, N, tick_format, label, spacing), which will instantiate a ipywidgets.widgets.widget_float.FloatSlider or a ipywidgets.widgets.widget_float.FloatLogSlider, depending on the spacing strategy. In particular:

    • default, min, maxfloat

      Default value, minimum value and maximum value of the slider, respectively. Must be finite numbers. The order of these 3 numbers is not important: the module will figure it out which is what.

    • Nint, optional

      Number of steps of the slider.

    • tick_formatstr or None, optional

      Provide a formatter for the tick value of the slider. Default to ".2f".

    • label: str, optional

      Custom text associated to the slider.

    • spacingstr, optional

      Specify the discretization spacing. Default to "linear", can be changed to "log".

Notes:

  1. parameters cannot be linked together (ie, one parameter cannot depend on another one).

  2. If a widget returns multiple numerical values (like panel.widgets.slider.RangeSlider or ipywidgets.widgets.widget_float.FloatRangeSlider), then a corresponding number of symbols must be provided.

Here follows a couple of examples. If imodule="panel":

import panel as pn
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: pn.widgets.FloatSlider(value=1, start=0, end=5), # same slider as above
    (c, d): pn.widgets.RangeSlider(value=(-1, 1), start=-3, end=3, step=0.1)
}

Or with imodule="ipywidgets":

import ipywidgets as w
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: w.FloatSlider(value=1, min=0, max=5), # same slider as above
    (c, d): w.FloatRangeSlider(value=(-1, 1), min=-3, max=3, step=0.1)
}

When instantiating a data series directly, params must be a dictionary mapping symbols to numerical values.

Let series be any data series. Then series.params returns a dictionary mapping symbols to numerical values.

polar_axisbool

If True, the backend will attempt to use polar axis, otherwise it uses cartesian axis. This is only supported for 2D plots. Default value: False.

rendering_kwdict

A dictionary of keyword arguments to be passed to the renderers in order to further customize the appearance of the surface. Here are some useful links for the supported plotting libraries:

show_in_legendbool

Toggle the visibility of the data series on the legend. Default value: True.

size

Set the size of the plot, (width, height). For Matplotlib, the size is measured in inches. For Bokeh, Plotly and K3D-Jupyter, the size is in pixel.

sum_boundint

When plotting sums, the expression will be pre-processed in order to replace lower/upper bounds set to +/- infinity with this +/- numerical value. Note: the higher this number, the slower the evaluation, but the more accurate the plot. It must be: 0 ≤ sum_bound < ∞. Default value: 1000.

surface_color

For back-compatibility with old sympy.plotting. Use rendering_kw in order to fully customize the appearance of the surface.

themestr

Theme to be used to style the figure. Depending on the backend being used, several themes may be available.

title

Title of the plot. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

txcallable

Numerical transformation function to be applied to the data on the x-axis.

tycallable

Numerical transformation function to be applied to the data on the y-axis.

tzcallable

Numerical transformation function to be applied to the data on the z-axis.

update_eventbool

If True and the backend supports such functionality, events like drag and zoom will trigger a recompute of the data series within the new axis limits. Default value: False.

use_cmbool

Toggle the use of a colormap. By default, some series might use a colormap to display the necessary data. Setting this attribute to False will inform the associated renderer to use solid color. Related parameters: color_func. Default value: False.

use_latexbool

Turn on/off the rendering of latex labels. If the backend doesn’t support latex, it will render the string representations instead. Default value: True.

x_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the x-axis.

xlabel

Label of the x-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

xlim

Limit the figure’s x-axis to the specified range. The tuple must be in the form (min_val, max_val).

xscaleNoneType, str

If the backend supports it, the x-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

y_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the y-axis.

ylabel

Label of the y-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

ylim

Limit the figure’s y-axis to the specified range. The tuple must be in the form (min_val, max_val).

yscaleNoneType, str

If the backend supports it, the y-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

zlabel

Label of the z-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

zlim

Limit the figure’s z-axis to the specified range. The tuple must be in the form (min_val, max_val).

zscaleNoneType, str

If the backend supports it, the z-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

See also

plot3d_parametric_list, plot3d_parametric_surface, plot3d_spherical
plot3d_revolution, plot3d_implicit, plot3d_list, plot_contour

Examples

>>> from sympy import symbols, cos, sin, pi, exp
>>> from spb import plot3d, multiples_of_pi_over_2
>>> x, y = symbols('x y')

(Source code)

Single plot with Matplotlib, with ticks formatted as multiples of pi/2.

>>> plot3d(
...     cos((x**2 + y**2)), (x, -pi, pi), (y, -pi, pi),
...     x_ticks_formatter=multiples_of_pi_over_2(),
...     y_ticks_formatter=multiples_of_pi_over_2(),
... )
Plot object containing:
[0]: cartesian surface: cos(x**2 + y**2) for x over (-pi, pi) and y over (-pi, pi)

(Source code, png)

../../_images/functions_3d-21.png

Single plot with Plotly, illustrating how to apply:

  • a color map: by default, it will map colors to the z values.

  • wireframe lines to better understand the discretization and curvature.

  • transformation to the discretized ranges in order to convert radians to degrees.

  • custom aspect ratio with Plotly.

from sympy import symbols, sin, cos, pi
from spb import plot3d, PB
import numpy as np
x, y = symbols("x, y")
expr = (cos(x) + sin(x) * sin(y) - sin(x) * cos(y))**2
plot3d(
    expr, (x, 0, pi), (y, 0, 2 * pi), backend=PB, use_cm=True,
    tx=np.rad2deg, ty=np.rad2deg, wireframe=True, wf_n1=20, wf_n2=20,
    xlabel="x [deg]", ylabel="y [deg]",
    aspect=dict(x=1.5, y=1.5, z=0.5))

(Source code, png)

Multiple plots with same range using color maps. By default, colors are mapped to the z values:

>>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5), use_cm=True)
Plot object containing:
[0]: cartesian surface: x*y for x over (-5, 5) and y over (-5, 5)
[1]: cartesian surface: -x*y for x over (-5, 5) and y over (-5, 5)

(Source code, png)

../../_images/functions_3d-41.png

Multiple plots with different ranges and solid colors.

>>> f = x**2 + y**2
>>> plot3d((f, (x, -3, 3), (y, -3, 3)),
...     (-f, (x, -5, 5), (y, -5, 5)))
Plot object containing:
[0]: cartesian surface: x**2 + y**2 for x over (-3, 3) and y over (-3, 3)
[1]: cartesian surface: -x**2 - y**2 for x over (-5, 5) and y over (-5, 5)

(Source code, png)

../../_images/functions_3d-5.png

Single plot with a polar discretization, a color function mapping a colormap to the radius. Note that the same result can be achieved with plot3d_revolution.

from sympy import *
from spb import *
import numpy as np
r, theta = symbols("r, theta")
expr = cos(r**2) * exp(-r / 3)
plot3d(expr, (r, 0, 5), (theta, 1.6 * pi, 2 * pi),
    backend=KB, is_polar=True, legend=True, grid=False,
    use_cm=True, color_func=lambda x, y, z: np.sqrt(x**2 + y**2),
    wireframe=True, wf_n1=30, wf_n2=10,
    wf_rendering_kw={"width": 0.005})

(Source code, small.png)

../../_images/functions_3d-6.small1.png

Plotting a numerical function instead of a symbolic expression:

>>> plot3d(lambda x, y: x * np.exp(-x**2 - y**2),
...     ("x", -3, 3), ("y", -3, 3), use_cm=True)  

(Source code, png)

../../_images/functions_3d-7.png

Interactive-widget plot. Refer to the interactive sub-module documentation to learn more about the params dictionary. This plot illustrates:

  • the use of prange (parametric plotting range).

  • the use of the params dictionary to specify sliders in their basic form: (default, min, max).

  • the use of panel.widgets.slider.RangeSlider, which is a 2-values widget.

from sympy import *
from spb import *
import panel as pn
x, y, a, b, c, d, e = symbols("x y a b c d e")
plot3d(
    cos(x**2 + y**2) * exp(-(x**2 + y**2) * a),
    prange(x, b, c), prange(y, d, e),
    params={
        a: (0.25, 0, 1),
        (b, c): pn.widgets.RangeSlider(
            value=(-2, 2), start=-4, end=4, step=0.1),
        (d, e): pn.widgets.RangeSlider(
            value=(-2, 2), start=-4, end=4, step=0.1),
    },
    backend=PB, use_cm=True, n=100, aspect=dict(x=1.5, y=1.5, z=0.75),
    wireframe=True, wf_n1=15, wf_n2=15, throttled=True)

(Source code, small.png)

../../_images/functions_3d-8.small.png
spb.plot_functions.functions_3d.plot3d_parametric_line(*args, **kwargs)[source]

Plots a 3D parametric line plot.

Typical usage examples are in the followings:

  • Plotting a single expression:

    plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)
    
  • Plotting a single expression with a custom label and rendering options:

    plot3d_parametric_line(expr_x, expr_y, expr_z, range,
       label [opt], rendering_kw [opt], **kwargs)
    
  • Plotting multiple expressions with the same ranges:

    plot3d_parametric_line((expr_x1, expr_y1, expr_z1),
       (expr_x2, expr_y2, expr_z2), ..., range, **kwargs)
    
  • Plotting multiple expressions with different ranges, custom labels and rendering options:

    plot3d_parametric_line(
       (expr_x1, expr_y1, expr_z1, range1, label1, rendering_kw1),
       (expr_x2, expr_y2, expr_z2, range2, label1, rendering_kw2),
       ..., **kwargs)
    
Parameters:
expr_x

The expression representing the component along the x-axis of the parametric function. It can either be a symbolic expression representing the function of one variable to be plotted, or a numerical function of one variable, supporting vectorization. In the latter case the following keyword arguments are not supported: params, sum_bound.

expr_y

The expression representing the component along the y-axis of the parametric function. It can either be a symbolic expression representing the function of one variable to be plotted, or a numerical function of one variable, supporting vectorization. In the latter case the following keyword arguments are not supported: params, sum_bound.

expr_z

The expression representing the component along the z-axis of the parametric function. It can either be a symbolic expression representing the function of one variable to be plotted, or a numerical function of one variable, supporting vectorization. In the latter case the following keyword arguments are not supported: params, sum_bound.

range_ptuple, Tuple

A 3-tuple (symb, min, max) denoting the range of the parameter. Default values: min=-10 and max=10.

labelstr

Set the label associated to this series, which will be eventually shown on the legend or colorbar.

aspectstr, tuple, list, dict

Set the aspect ratio.

Possible values for Matplotlib (only works for a 2D plot):

  • "auto": Matplotlib will fit the plot in the vibile area.

  • "equal": sets equal spacing.

  • tuple containing 2 float numbers, from which the aspect ratio is computed. This only works for 2D plots.

Possible values for Plotly:

  • "equal": sets equal spacing on the axis of a 2D plot.

  • For 3D plots:

    • "cube": fix the ratio to be a cube

    • "data": draw axes in proportion of their ranges

    • "auto": automatically produce something that is well proportioned using ‘data’ as the default.

    • manually set the aspect ratio by providing a dictionary. For example: dict(x=1, y=1, z=2) forces the z-axis to appear twice as big as the other two.

Possible values for Bokeh:

  • "equal": sets equal spacing.

ax

An existing Matplotlib’s Axes over which the symbolic expressions will be plotted.

axisbool

Show the axis in the figure. Default value: True.

axis_centerstr, tuple

Set the location of the intersection between the horizontal and vertical axis in a 2D plot. It only works with Matplotlib and it can receive the following values:

  • None: traditional layout, with the horizontal axis fixed on the bottom and the vertical axis fixed on the left. This is the default value.

  • a tuple (x, y) specifying the exact intersection point.

  • 'center': center of the current plot area.

  • 'auto': the intersection point is automatically computed.

camera

Set the camera position for 3D plots.

For Matplotlib, it can be a dictionary of keyword arguments that will be passed to the Axes3D.view_init method. Refer to the following link for more information: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html#mpl_toolkits.mplot3d.axes3d.Axes3D.view_init

For Plotly, it can be a dictionary of keyword arguments that will be passed to the layout’s scene_camera. Refer to the following link for more information: https://plotly.com/python/3d-camera-controls/

For K3D-Jupyter, it is list of 9 numbers, namely:

  • x_cam, y_cam, z_cam: the position of the camera in the scene

  • x_tar, y_tar, z_tar: the position of the target of the camera

  • x_up, y_up, z_up: components of the up vector

color_func

Define a custom color mapping when use_cm=True. It can either be:

  • A numerical function supporting vectorization. The arity can be:

    • 1 argument: f(t), where t is the parameter.

    • 3 arguments: f(x, y, z) where x, y, z are the coordinates of the points.

    • 4 arguments: f(x, y, z, t).

  • A symbolic expression having at most as many free symbols as expr_x or expr_y or expr_z.

  • None: the default value (color mapping according to the parameter).

Alias of this parameters: tp.

colorbarbool

Toggle the visibility of the colorbar associated to the current data series. Note that a colorbar is only visible if use_cm=True and color_func is not None. Default value: True.

colorbar_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values on the colorbar at each multiple of a specified quantity. This only works when use_cm=True.

colorlooplist, tuple

List of colors to be used in line plots or solid color surfaces.

colormapslist, tuple

List of color maps to render surfaces.

cyclic_colormapslist, tuple

List of cyclic color maps to render complex series (the phase/argument ranges over [-pi, pi]).

detect_polesbool, str

Chose whether to detect and correctly plot the roots of the denominator. There are two algorithms at work:

  1. based on the gradient of the numerical data, it introduces NaN values at locations where the steepness is greater than some threshold. This splits the line into multiple segments. To improve detection, increase the number of discretization points n and/or change the value of eps. This algorithm can be used to visualize jump discontinuities as well as essential discontinuities.

  2. a symbolic approach based on the continuous_domain function from the sympy.calculus.util module, which computes the locations of essential discontinuities. If any are found, vertical lines will be shown.

Possible options:

  • False: No poles detection

  • True: Poles detection with the numerical algorithm

  • ‘symbolic’: Poles detection with numerical and symbolic algorithms

Default value: False.

epsfloat

An arbitrary small value used by the detect_poles numerical algorithm. Before changing this value, it is recommended to increase the number of discretization points. Related parameters: detect_poles. It must be: 0 ≤ eps < ∞. Default value: 0.01.

excludelist

A list of numerical values along the parameter which are going to be excluded from the evaluation. In practice, it introduces discontinuities in the resulting line.

fig

Get or set the figure where to plot into.

force_real_evalbool

By default, numerical evaluation is performed over complex numbers, which is slower but produces correct results. However, when the symbolic expression is converted to a numerical function with lambdify, the resulting function may not like to be evaluated over complex numbers. In such cases, forcing the evaluation to be performed over real numbers might be a good choice. The plotting module should be able to detect such occurences and automatically activate this option. If that is not the case, or evaluation performance is of paramount importance, set this parameter to True, but be aware that it might produce wrong results. Default value: False.

gridbool, dict

Toggle the visibility of major grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

hookslist

List of functions expecting one argument, the current plot object, which allows users to further customize the appearance of the plot before it is shown on the screen. The hooks are executed:

  1. after the figure has been initialized and populated with numerical data.

  2. after the existing renderers update the visualization because the user interacted with some widget.

Note: let p be the plot object. Then, the user can access the figure with p.fig. In case of spb.backends.matplotlib.MatplotlibBackend, the user can also retrieve the axes in which data was added with p.ax.

is_filledbool

Whether scatter’s markers are filled or void. Default value: True.

is_scatterbool

If True it represent a scatter plot, otherwise a continuous line. Default value: False.

legendbool

Toggle the visibility of the legend. If None, the backend will automatically determine if it is appropriate to show it. Default value: None.

line_color

For back-compatibility with old sympy.plotting. Use rendering_kw in order to fully customize the appearance of the line/scatter.

minor_gridbool, dict

Toggle the visibility of minor grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

modules

Specify the evaluation modules to be used by lambdify. If not specified, the evaluation will be done with NumPy/SciPy.

n1int

Number of discretization points along the parameter to be used in the evaluation. An alias of this parameter is n. Related parameters: xscale. It must be: 2 ≤ n1 < ∞. Default value: 1000.

only_integersbool

Discretize the domain using only integer numbers. When this parameter is True, the number of discretization points is choosen by the algorithm. Default value: False.

paramsdict, optional

A dictionary mapping symbols to parameters. If provided, this dictionary enables the interactive-widgets plot.

When calling a plotting function, the parameter can be specified with:

  • a widget from the ipywidgets module.

  • a widget from the panel module.

  • a tuple of the form:

    (default, min, max, N, tick_format, label, spacing), which will instantiate a ipywidgets.widgets.widget_float.FloatSlider or a ipywidgets.widgets.widget_float.FloatLogSlider, depending on the spacing strategy. In particular:

    • default, min, maxfloat

      Default value, minimum value and maximum value of the slider, respectively. Must be finite numbers. The order of these 3 numbers is not important: the module will figure it out which is what.

    • Nint, optional

      Number of steps of the slider.

    • tick_formatstr or None, optional

      Provide a formatter for the tick value of the slider. Default to ".2f".

    • label: str, optional

      Custom text associated to the slider.

    • spacingstr, optional

      Specify the discretization spacing. Default to "linear", can be changed to "log".

Notes:

  1. parameters cannot be linked together (ie, one parameter cannot depend on another one).

  2. If a widget returns multiple numerical values (like panel.widgets.slider.RangeSlider or ipywidgets.widgets.widget_float.FloatRangeSlider), then a corresponding number of symbols must be provided.

Here follows a couple of examples. If imodule="panel":

import panel as pn
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: pn.widgets.FloatSlider(value=1, start=0, end=5), # same slider as above
    (c, d): pn.widgets.RangeSlider(value=(-1, 1), start=-3, end=3, step=0.1)
}

Or with imodule="ipywidgets":

import ipywidgets as w
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: w.FloatSlider(value=1, min=0, max=5), # same slider as above
    (c, d): w.FloatRangeSlider(value=(-1, 1), min=-3, max=3, step=0.1)
}

When instantiating a data series directly, params must be a dictionary mapping symbols to numerical values.

Let series be any data series. Then series.params returns a dictionary mapping symbols to numerical values.

polar_axisbool

If True, the backend will attempt to use polar axis, otherwise it uses cartesian axis. This is only supported for 2D plots. Default value: False.

rendering_kwdict

A dictionary of keyword arguments to be passed to the renderers in order to further customize the appearance of the line. Here are some useful links for the supported plotting libraries:

show_in_legendbool

Toggle the visibility of the data series on the legend. Default value: True.

size

Set the size of the plot, (width, height). For Matplotlib, the size is measured in inches. For Bokeh, Plotly and K3D-Jupyter, the size is in pixel.

sum_boundint

When plotting sums, the expression will be pre-processed in order to replace lower/upper bounds set to +/- infinity with this +/- numerical value. Note: the higher this number, the slower the evaluation, but the more accurate the plot. It must be: 0 ≤ sum_bound < ∞. Default value: 1000.

themestr

Theme to be used to style the figure. Depending on the backend being used, several themes may be available.

title

Title of the plot. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

txcallable

Numerical transformation function to be applied to the data on the x-axis.

tycallable

Numerical transformation function to be applied to the data on the y-axis.

tzcallable

Numerical transformation function to be applied to the data on the z-axis.

update_eventbool

If True and the backend supports such functionality, events like drag and zoom will trigger a recompute of the data series within the new axis limits. Default value: False.

use_cmbool

Toggle the use of a colormap. By default, some series might use a colormap to display the necessary data. Setting this attribute to False will inform the associated renderer to use solid color. Related parameters: color_func. Default value: False.

use_latexbool

Turn on/off the rendering of latex labels. If the backend doesn’t support latex, it will render the string representations instead. Default value: True.

x_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the x-axis.

xlabel

Label of the x-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

xlim

Limit the figure’s x-axis to the specified range. The tuple must be in the form (min_val, max_val).

xscaleNoneType, str

If the backend supports it, the x-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

y_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the y-axis.

ylabel

Label of the y-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

ylim

Limit the figure’s y-axis to the specified range. The tuple must be in the form (min_val, max_val).

yscaleNoneType, str

If the backend supports it, the y-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

zlabel

Label of the z-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

zlim

Limit the figure’s z-axis to the specified range. The tuple must be in the form (min_val, max_val).

zscaleNoneType, str

If the backend supports it, the z-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

Examples

>>> from sympy import symbols, cos, sin, pi, root
>>> from spb import plot3d_parametric_line
>>> t = symbols('t')

(Source code)

Single plot.

>>> plot3d_parametric_line(cos(t), sin(t), t, (t, -5, 5))
Plot object containing:
[0]: 3D parametric cartesian line: (cos(t), sin(t), t) for t over (-5, 5)

(Source code, png)

../../_images/functions_3d-10.png

Customize the appearance by setting a label to the colorbar, changing the colormap, the line width, and the ticks on the colorbar.

>>> plot3d_parametric_line(
...     3 * sin(t) + 2 * sin(3 * t), cos(t) - 2 * cos(3 * t), cos(5 * t),
...     (t, 0, 2 * pi), "t [rad]", {"cmap": "hsv", "lw": 1.5},
...     aspect="equal",
...     colorbar_ticks_formatter=multiples_of_pi_over_2()))
Plot object containing:
[0]: 3D parametric cartesian line: (3*sin(t) + 2*sin(3*t), cos(t) - 2*cos(3*t), cos(5*t)) for t over (0, 2*pi)

(Source code)

Plot multiple parametric 3D lines with different ranges:

>>> a, b, n = 2, 1, 4
>>> p, r, s = symbols("p r s")
>>> xp = a * cos(p) * cos(n * p)
>>> yp = a * sin(p) * cos(n * p)
>>> zp = b * cos(n * p)**2 + pi
>>> xr = root(r, 3) * cos(r)
>>> yr = root(r, 3) * sin(r)
>>> zr = 0
>>> plot3d_parametric_line(
...     (xp, yp, zp, (p, 0, pi if n % 2 == 1 else 2 * pi), "petals"),
...     (xr, yr, zr, (r, 0, 6*pi), "roots"),
...     (-sin(s)/3, 0, s, (s, 0, pi), "stem"), use_cm=False)
Plot object containing:
[0]: 3D parametric cartesian line: (2*cos(p)*cos(4*p), 2*sin(p)*cos(4*p), cos(4*p)**2 + pi) for p over (0, 2*pi)
[1]: 3D parametric cartesian line: (r**(1/3)*cos(r), r**(1/3)*sin(r), 0) for r over (0, 6*pi)
[2]: 3D parametric cartesian line: (-sin(s)/3, 0, s) for s over (0, pi)

(Source code, png)

../../_images/functions_3d-121.png

Plotting a numerical function instead of a symbolic expression, using Plotly:

from spb import plot3d_parametric_line, PB
import numpy as np
fx = lambda t: (1 + 0.25 * np.cos(75 * t)) * np.cos(t)
fy = lambda t: (1 + 0.25 * np.cos(75 * t)) * np.sin(t)
fz = lambda t: t + 2 * np.sin(75 * t)
plot3d_parametric_line(fx, fy, fz, ("t", 0, 6 * np.pi),
    {"line": {"colorscale": "bluered"}},
    title="Helical Toroid", backend=PB, n=1e04)

(Source code, png)

Interactive-widget plot of the parametric line over a tennis ball. Refer to the interactive sub-module documentation to learn more about the params dictionary. This plot illustrates:

  • combining together different plots.

  • the use of prange (parametric plotting range).

  • the use of the params dictionary to specify sliders in their basic form: (default, min, max).

from sympy import *
from spb import *
import k3d
a, b, s, e, t = symbols("a, b, s, e, t")
c = 2 * sqrt(a * b)
r = a + b
params = {
    a: (1.5, 0, 2),
    b: (1, 0, 2),
    s: (0, 0, 2),
    e: (2, 0, 2)
}
sphere = plot3d_revolution(
    (r * cos(t), r * sin(t)), (t, 0, pi),
    params=params, n=50, parallel_axis="x",
    backend=KB,
    show_curve=False, show=False,
    rendering_kw={"color":0x353535})
line = plot3d_parametric_line(
    a * cos(t) + b * cos(3 * t),
    a * sin(t) - b * sin(3 * t),
    c * sin(2 * t), prange(t, s*pi, e*pi),
    {"color_map": k3d.matplotlib_color_maps.Summer}, params=params,
    backend=KB, show=False)
(line + sphere).show()

(Source code, small.png)

../../_images/functions_3d-14.small.png
spb.plot_functions.functions_3d.plot3d_parametric_surface(*args, **kwargs)[source]

Plots a 3D parametric surface plot.

Typical usage examples are in the followings:

  • Plotting a single expression:

    plot3d_parametric_surface(
           expr_x, expr_y, expr_z, range_u, range_v, label, **kwargs)
    
  • Plotting multiple expressions with the same ranges:

    plot3d_parametric_surface((expr_x1, expr_y1, expr_z1),
       (expr_x2, expr_y2, expr_z2), range_u, range_v, **kwargs)
    
  • Plotting multiple expressions with different ranges, custom labels and rendering option:

    plot3d_parametric_surface(
       (expr_x1, expr_y1, expr_z1, range_u1, range_v1,
           label1 [opt], rendering_kw1 [opt]),
       (expr_x2, expr_y2, expr_z2, range_u2, range_v2,
           label2 [opt], rendering_kw2 [opt]), **kwargs)`
    

Note: it is important to specify both the ranges.

Parameters:
expr_x

The expression representing the component along the x-axis of the parametric function. It can be a:

  • Symbolic expression.

  • Numerical function of two variable, f(u, v), supporting vectorization. In this case the following keyword arguments are not supported: params.

expr_y

The expression representing the component along the y-axis of the parametric function. It can be a:

  • Symbolic expression.

  • Numerical function of two variable, f(u, v), supporting vectorization. In this case the following keyword arguments are not supported: params.

expr_z

The expression representing the component along the z-axis of the parametric function. It can be a:

  • Symbolic expression.

  • Numerical function of two variable, f(u, v), supporting vectorization. In this case the following keyword arguments are not supported: params.

range_utuple, Tuple

A 3-tuple (symb, min, max) denoting the range of the u parameter. Default values: min=-10 and max=10.

range_vtuple, Tuple

A 3-tuple (symb, min, max) denoting the range of the v parameter. Default values: min=-10 and max=10.

labelstr

Set the label associated to this series, which will be eventually shown on the legend or colorbar.

aspectstr, tuple, list, dict

Set the aspect ratio.

Possible values for Matplotlib (only works for a 2D plot):

  • "auto": Matplotlib will fit the plot in the vibile area.

  • "equal": sets equal spacing.

  • tuple containing 2 float numbers, from which the aspect ratio is computed. This only works for 2D plots.

Possible values for Plotly:

  • "equal": sets equal spacing on the axis of a 2D plot.

  • For 3D plots:

    • "cube": fix the ratio to be a cube

    • "data": draw axes in proportion of their ranges

    • "auto": automatically produce something that is well proportioned using ‘data’ as the default.

    • manually set the aspect ratio by providing a dictionary. For example: dict(x=1, y=1, z=2) forces the z-axis to appear twice as big as the other two.

Possible values for Bokeh:

  • "equal": sets equal spacing.

ax

An existing Matplotlib’s Axes over which the symbolic expressions will be plotted.

axisbool

Show the axis in the figure. Default value: True.

axis_centerstr, tuple

Set the location of the intersection between the horizontal and vertical axis in a 2D plot. It only works with Matplotlib and it can receive the following values:

  • None: traditional layout, with the horizontal axis fixed on the bottom and the vertical axis fixed on the left. This is the default value.

  • a tuple (x, y) specifying the exact intersection point.

  • 'center': center of the current plot area.

  • 'auto': the intersection point is automatically computed.

camera

Set the camera position for 3D plots.

For Matplotlib, it can be a dictionary of keyword arguments that will be passed to the Axes3D.view_init method. Refer to the following link for more information: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html#mpl_toolkits.mplot3d.axes3d.Axes3D.view_init

For Plotly, it can be a dictionary of keyword arguments that will be passed to the layout’s scene_camera. Refer to the following link for more information: https://plotly.com/python/3d-camera-controls/

For K3D-Jupyter, it is list of 9 numbers, namely:

  • x_cam, y_cam, z_cam: the position of the camera in the scene

  • x_tar, y_tar, z_tar: the position of the target of the camera

  • x_up, y_up, z_up: components of the up vector

color_func

Define the surface color mapping when use_cm=True. It can either be:

  • None: the default value (color mapping according to the z coordinate).

  • A numerical function supporting vectorization. The arity can be:

    • 1 argument: f(u), where u is the first parameter.

    • 2 arguments: f(u, v) where u, v are the parameters.

    • 3 arguments: f(x, y, z) where x, y, z are the coordinates of the points.

    • 5 arguments: f(x, y, z, u, v).

  • A symbolic expression having at most as many free symbols as expr_x or expr_y or expr_z.

colorbarbool

Toggle the visibility of the colorbar associated to the current data series. Note that a colorbar is only visible if use_cm=True and color_func is not None. Default value: True.

colorbar_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values on the colorbar at each multiple of a specified quantity. This only works when use_cm=True.

colorlooplist, tuple

List of colors to be used in line plots or solid color surfaces.

colormapslist, tuple

List of color maps to render surfaces.

cyclic_colormapslist, tuple

List of cyclic color maps to render complex series (the phase/argument ranges over [-pi, pi]).

fig

Get or set the figure where to plot into.

force_real_evalbool

By default, numerical evaluation is performed over complex numbers, which is slower but produces correct results. However, when the symbolic expression is converted to a numerical function with lambdify, the resulting function may not like to be evaluated over complex numbers. In such cases, forcing the evaluation to be performed over real numbers might be a good choice. The plotting module should be able to detect such occurences and automatically activate this option. If that is not the case, or evaluation performance is of paramount importance, set this parameter to True, but be aware that it might produce wrong results. Default value: False.

gridbool, dict

Toggle the visibility of major grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

hookslist

List of functions expecting one argument, the current plot object, which allows users to further customize the appearance of the plot before it is shown on the screen. The hooks are executed:

  1. after the figure has been initialized and populated with numerical data.

  2. after the existing renderers update the visualization because the user interacted with some widget.

Note: let p be the plot object. Then, the user can access the figure with p.fig. In case of spb.backends.matplotlib.MatplotlibBackend, the user can also retrieve the axes in which data was added with p.ax.

legendbool

Toggle the visibility of the legend. If None, the backend will automatically determine if it is appropriate to show it. Default value: None.

minor_gridbool, dict

Toggle the visibility of minor grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

modules

Specify the evaluation modules to be used by lambdify. If not specified, the evaluation will be done with NumPy/SciPy.

n1int

Number of discretization points along the first parameter to be used in the evaluation. Related parameters: xscale. It must be: 2 ≤ n1 < ∞. Default value: 100.

n2int

Number of discretization points along the second parameter to be used in the evaluation. Related parameters: yscale. It must be: 2 ≤ n2 < ∞. Default value: 100.

only_integersbool

Discretize the domain using only integer numbers. When this parameter is True, the number of discretization points is choosen by the algorithm. Default value: False.

paramsdict, optional

A dictionary mapping symbols to parameters. If provided, this dictionary enables the interactive-widgets plot.

When calling a plotting function, the parameter can be specified with:

  • a widget from the ipywidgets module.

  • a widget from the panel module.

  • a tuple of the form:

    (default, min, max, N, tick_format, label, spacing), which will instantiate a ipywidgets.widgets.widget_float.FloatSlider or a ipywidgets.widgets.widget_float.FloatLogSlider, depending on the spacing strategy. In particular:

    • default, min, maxfloat

      Default value, minimum value and maximum value of the slider, respectively. Must be finite numbers. The order of these 3 numbers is not important: the module will figure it out which is what.

    • Nint, optional

      Number of steps of the slider.

    • tick_formatstr or None, optional

      Provide a formatter for the tick value of the slider. Default to ".2f".

    • label: str, optional

      Custom text associated to the slider.

    • spacingstr, optional

      Specify the discretization spacing. Default to "linear", can be changed to "log".

Notes:

  1. parameters cannot be linked together (ie, one parameter cannot depend on another one).

  2. If a widget returns multiple numerical values (like panel.widgets.slider.RangeSlider or ipywidgets.widgets.widget_float.FloatRangeSlider), then a corresponding number of symbols must be provided.

Here follows a couple of examples. If imodule="panel":

import panel as pn
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: pn.widgets.FloatSlider(value=1, start=0, end=5), # same slider as above
    (c, d): pn.widgets.RangeSlider(value=(-1, 1), start=-3, end=3, step=0.1)
}

Or with imodule="ipywidgets":

import ipywidgets as w
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: w.FloatSlider(value=1, min=0, max=5), # same slider as above
    (c, d): w.FloatRangeSlider(value=(-1, 1), min=-3, max=3, step=0.1)
}

When instantiating a data series directly, params must be a dictionary mapping symbols to numerical values.

Let series be any data series. Then series.params returns a dictionary mapping symbols to numerical values.

polar_axisbool

If True, the backend will attempt to use polar axis, otherwise it uses cartesian axis. This is only supported for 2D plots. Default value: False.

rendering_kwdict

A dictionary of keyword arguments to be passed to the renderers in order to further customize the appearance of the surface. Here are some useful links for the supported plotting libraries:

show_in_legendbool

Toggle the visibility of the data series on the legend. Default value: True.

size

Set the size of the plot, (width, height). For Matplotlib, the size is measured in inches. For Bokeh, Plotly and K3D-Jupyter, the size is in pixel.

sum_boundint

When plotting sums, the expression will be pre-processed in order to replace lower/upper bounds set to +/- infinity with this +/- numerical value. Note: the higher this number, the slower the evaluation, but the more accurate the plot. It must be: 0 ≤ sum_bound < ∞. Default value: 1000.

surface_color

For back-compatibility with old sympy.plotting. Use rendering_kw in order to fully customize the appearance of the surface.

themestr

Theme to be used to style the figure. Depending on the backend being used, several themes may be available.

title

Title of the plot. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

txcallable

Numerical transformation function to be applied to the data on the x-axis.

tycallable

Numerical transformation function to be applied to the data on the y-axis.

tzcallable

Numerical transformation function to be applied to the data on the z-axis.

update_eventbool

If True and the backend supports such functionality, events like drag and zoom will trigger a recompute of the data series within the new axis limits. Default value: False.

use_cmbool

Toggle the use of a colormap. By default, some series might use a colormap to display the necessary data. Setting this attribute to False will inform the associated renderer to use solid color. Related parameters: color_func. Default value: False.

use_latexbool

Turn on/off the rendering of latex labels. If the backend doesn’t support latex, it will render the string representations instead. Default value: True.

x_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the x-axis.

xlabel

Label of the x-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

xlim

Limit the figure’s x-axis to the specified range. The tuple must be in the form (min_val, max_val).

xscaleNoneType, str

If the backend supports it, the x-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

y_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the y-axis.

ylabel

Label of the y-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

ylim

Limit the figure’s y-axis to the specified range. The tuple must be in the form (min_val, max_val).

yscaleNoneType, str

If the backend supports it, the y-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

zlabel

Label of the z-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

zlim

Limit the figure’s z-axis to the specified range. The tuple must be in the form (min_val, max_val).

zscaleNoneType, str

If the backend supports it, the z-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

Examples

>>> from sympy import symbols, cos, sin, pi, I, sqrt, atan2, re, im
>>> from spb import plot3d_parametric_surface
>>> u, v = symbols('u v')

(Source code)

Plot a parametric surface:

>>> plot3d_parametric_surface(
...     u * cos(v), u * sin(v), u * cos(4 * v) / 2,
...     (u, 0, pi), (v, 0, 2*pi),
...     use_cm=False, title="Sinusoidal Cone")
Plot object containing:
[0]: parametric cartesian surface: (u*cos(v), u*sin(v), u*cos(4*v)/2) for u over (0, pi) and v over (0, 2*pi)

(Source code, png)

../../_images/functions_3d-16.png

Customize the appearance of the surface by changing the colormap. Apply a color function mapping the v values. Activate the wireframe to better visualize the parameterization.

from sympy import *
from spb import *
var("u, v")

x = (1 + v / 2 * cos(u / 2)) * cos(u)
y = (1 + v / 2 * cos(u / 2)) * sin(u)
z = v / 2 * sin(u / 2)
plot3d_parametric_surface(
    x, y, z, (u, 0, 2*pi), (v, -1, 1),
    "v", {"colorscale": "mygbm"},
    use_cm=True, color_func=lambda u, v: u,
    wireframe=True, wf_n1=20,
    title="Möbius strip",
    colorbar_ticks_formatter=multiples_of_pi_over_2(label="π"),
    backend=PB)

(Source code, png)

Riemann surfaces of the real part of the multivalued function z**n, using Plotly:

from sympy import symbols, sqrt, re, im, pi, atan2, sin, cos, I
from spb import plot3d_parametric_surface, PB
r, theta, x, y = symbols("r, theta, x, y", real=True)
mag = lambda z: sqrt(re(z)**2 + im(z)**2)
phase = lambda z, k=0: atan2(im(z), re(z)) + 2 * k * pi
n = 2 # exponent (integer)
z = x + I * y # cartesian
d = {x: r * cos(theta), y: r * sin(theta)} # cartesian to polar
branches = [(mag(z)**(1 / n) * cos(phase(z, i) / n)).subs(d)
    for i in range(n)]
exprs = [(r * cos(theta), r * sin(theta), rb) for rb in branches]
plot3d_parametric_surface(*exprs, (r, 0, 3), (theta, -pi, pi),
    backend=PB, wireframe=True, wf_n2=20, zlabel="f(z)",
    label=["branch %s" % (i + 1) for i in range(len(branches))])

(Source code, png)

Plotting a numerical function instead of a symbolic expression.

from spb import *
import numpy as np
fx = lambda u, v: (4 + np.cos(u)) * np.cos(v)
fy = lambda u, v: (4 + np.cos(u)) * np.sin(v)
fz = lambda u, v: np.sin(u)
plot3d_parametric_surface(fx, fy, fz, ("u", 0, 2 * np.pi),
    ("v", 0, 2 * np.pi), zlim=(-2.5, 2.5), title="Torus",
    backend=KB, grid=False)

(Source code, small.png)

../../_images/functions_3d-19.small.png

Interactive-widget plot. Refer to the interactive sub-module documentation to learn more about the params dictionary. This plot illustrates:

  • the use of prange (parametric plotting range).

  • the use of the params dictionary to specify sliders in their basic form: (default, min, max).

from sympy import *
from spb import *
import k3d
alpha, u, v, up, vp = symbols("alpha u v u_p v_p")
plot3d_parametric_surface((
        exp(u) * cos(v - alpha) / 2 + exp(-u) * cos(v + alpha) / 2,
        exp(u) * sin(v - alpha) / 2 + exp(-u) * sin(v + alpha) / 2,
        cos(alpha) * u + sin(alpha) * v
    ),
    prange(u, -up, up), prange(v, 0, vp * pi),
    backend=KB,
    use_cm=True,
    color_func=lambda u, v: v,
    rendering_kw={"color_map": k3d.colormaps.paraview_color_maps.Hue_L60},
    wireframe=True, wf_n2=15, wf_rendering_kw={"width": 0.005},
    grid=False, n=50,
    params={
        alpha: (0, 0, pi),
        up: (1, 0, 2),
        vp: (2, 0, 2),
    },
    title="Catenoid \, to \, Right \, Helicoid \, Transformation")

(Source code, small.png)

../../_images/functions_3d-20.small.png

Interactive-widget plot. Refer to the interactive sub-module documentation to learn more about the params dictionary. Note that the plot’s creation might be slow due to the wireframe lines.

from sympy import *
from spb import *
import panel as pn
n, u, v = symbols("n, u, v")
x = v * cos(u)
y = v * sin(u)
z = sin(n * u)
plot3d_parametric_surface(
    (x, y, z, (u, 0, 2*pi), (v, -1, 0)),
    params = {
        n: pn.widgets.IntInput(value=3, name="n")
    },
    backend=KB,
    use_cm=True,
    title="Plücker's \, conoid",
    wireframe=True,
    wf_rendering_kw={"width": 0.004},
    wf_n1=75, wf_n2=6, imodule="panel"
)

(Source code, small.png)

../../_images/functions_3d-21.small.png
spb.plot_functions.functions_3d.plot3d_spherical(*args, **kwargs)[source]

Plots a radius as a function of the spherical coordinates theta and phi.

Typical usage examples are in the followings:

  • Plotting a single expression.:

    plot3d_spherical(r, range_theta, range_phi, **kwargs)
    
  • Plotting multiple expressions with the same ranges.:

    plot3d_spherical(r1, r2, range_theta, range_phi, **kwargs)
    
  • Plotting multiple expressions with different ranges, custom labels and rendering options:

    plot3d_spherical(
       (r1, range_theta1, range_phi1, label1 [opt], rendering_kw1 [opt]),
       (r2, range_theta2, range_phi2, label2 [opt], rendering_kw2 [opt]),
       ..., **kwargs)
    

Note: it is important to specify both the ranges.

Parameters:
rExpr or callable

Expression representing the radius. It can be a:

  • Symbolic expression.

  • Numerical function of two variable, f(theta, phi), supporting vectorization. In this case the following keyword arguments are not supported: params.

range_thetatuple

A 3-tuple (symbol, min, max) denoting the range of the polar angle, which is limited in [0, pi]. Consider a sphere:

  • theta=0 indicates the north pole.

  • theta=pi/2 indicates the equator.

  • theta=pi indicates the south pole.

range_phituple

A 3-tuple (symbol, min, max) denoting the range of the azimuthal angle, which is limited in [0, 2*pi].

labelstr

Set the label associated to this series, which will be eventually shown on the legend or colorbar.

aspectstr, tuple, list, dict

Set the aspect ratio.

Possible values for Matplotlib (only works for a 2D plot):

  • "auto": Matplotlib will fit the plot in the vibile area.

  • "equal": sets equal spacing.

  • tuple containing 2 float numbers, from which the aspect ratio is computed. This only works for 2D plots.

Possible values for Plotly:

  • "equal": sets equal spacing on the axis of a 2D plot.

  • For 3D plots:

    • "cube": fix the ratio to be a cube

    • "data": draw axes in proportion of their ranges

    • "auto": automatically produce something that is well proportioned using ‘data’ as the default.

    • manually set the aspect ratio by providing a dictionary. For example: dict(x=1, y=1, z=2) forces the z-axis to appear twice as big as the other two.

Possible values for Bokeh:

  • "equal": sets equal spacing.

ax

An existing Matplotlib’s Axes over which the symbolic expressions will be plotted.

axisbool

Show the axis in the figure. Default value: True.

axis_centerstr, tuple

Set the location of the intersection between the horizontal and vertical axis in a 2D plot. It only works with Matplotlib and it can receive the following values:

  • None: traditional layout, with the horizontal axis fixed on the bottom and the vertical axis fixed on the left. This is the default value.

  • a tuple (x, y) specifying the exact intersection point.

  • 'center': center of the current plot area.

  • 'auto': the intersection point is automatically computed.

camera

Set the camera position for 3D plots.

For Matplotlib, it can be a dictionary of keyword arguments that will be passed to the Axes3D.view_init method. Refer to the following link for more information: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html#mpl_toolkits.mplot3d.axes3d.Axes3D.view_init

For Plotly, it can be a dictionary of keyword arguments that will be passed to the layout’s scene_camera. Refer to the following link for more information: https://plotly.com/python/3d-camera-controls/

For K3D-Jupyter, it is list of 9 numbers, namely:

  • x_cam, y_cam, z_cam: the position of the camera in the scene

  • x_tar, y_tar, z_tar: the position of the target of the camera

  • x_up, y_up, z_up: components of the up vector

color_func

Define the surface color mapping when use_cm=True. It can either be:

  • None: the default value (color mapping according to the z coordinate).

  • A numerical function supporting vectorization. The arity can be:

    • 1 argument: f(u), where u is the first parameter.

    • 2 arguments: f(u, v) where u, v are the parameters.

    • 3 arguments: f(x, y, z) where x, y, z are the coordinates of the points.

    • 5 arguments: f(x, y, z, u, v).

  • A symbolic expression having at most as many free symbols as expr_x or expr_y or expr_z.

colorbarbool

Toggle the visibility of the colorbar associated to the current data series. Note that a colorbar is only visible if use_cm=True and color_func is not None. Default value: True.

colorbar_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values on the colorbar at each multiple of a specified quantity. This only works when use_cm=True.

colorlooplist, tuple

List of colors to be used in line plots or solid color surfaces.

colormapslist, tuple

List of color maps to render surfaces.

cyclic_colormapslist, tuple

List of cyclic color maps to render complex series (the phase/argument ranges over [-pi, pi]).

fig

Get or set the figure where to plot into.

force_real_evalbool

By default, numerical evaluation is performed over complex numbers, which is slower but produces correct results. However, when the symbolic expression is converted to a numerical function with lambdify, the resulting function may not like to be evaluated over complex numbers. In such cases, forcing the evaluation to be performed over real numbers might be a good choice. The plotting module should be able to detect such occurences and automatically activate this option. If that is not the case, or evaluation performance is of paramount importance, set this parameter to True, but be aware that it might produce wrong results. Default value: False.

gridbool, dict

Toggle the visibility of major grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

hookslist

List of functions expecting one argument, the current plot object, which allows users to further customize the appearance of the plot before it is shown on the screen. The hooks are executed:

  1. after the figure has been initialized and populated with numerical data.

  2. after the existing renderers update the visualization because the user interacted with some widget.

Note: let p be the plot object. Then, the user can access the figure with p.fig. In case of spb.backends.matplotlib.MatplotlibBackend, the user can also retrieve the axes in which data was added with p.ax.

legendbool

Toggle the visibility of the legend. If None, the backend will automatically determine if it is appropriate to show it. Default value: None.

minor_gridbool, dict

Toggle the visibility of minor grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

modules

Specify the evaluation modules to be used by lambdify. If not specified, the evaluation will be done with NumPy/SciPy.

n1int

Number of discretization points along the first parameter to be used in the evaluation. Related parameters: xscale. It must be: 2 ≤ n1 < ∞. Default value: 100.

n2int

Number of discretization points along the second parameter to be used in the evaluation. Related parameters: yscale. It must be: 2 ≤ n2 < ∞. Default value: 100.

only_integersbool

Discretize the domain using only integer numbers. When this parameter is True, the number of discretization points is choosen by the algorithm. Default value: False.

paramsdict, optional

A dictionary mapping symbols to parameters. If provided, this dictionary enables the interactive-widgets plot.

When calling a plotting function, the parameter can be specified with:

  • a widget from the ipywidgets module.

  • a widget from the panel module.

  • a tuple of the form:

    (default, min, max, N, tick_format, label, spacing), which will instantiate a ipywidgets.widgets.widget_float.FloatSlider or a ipywidgets.widgets.widget_float.FloatLogSlider, depending on the spacing strategy. In particular:

    • default, min, maxfloat

      Default value, minimum value and maximum value of the slider, respectively. Must be finite numbers. The order of these 3 numbers is not important: the module will figure it out which is what.

    • Nint, optional

      Number of steps of the slider.

    • tick_formatstr or None, optional

      Provide a formatter for the tick value of the slider. Default to ".2f".

    • label: str, optional

      Custom text associated to the slider.

    • spacingstr, optional

      Specify the discretization spacing. Default to "linear", can be changed to "log".

Notes:

  1. parameters cannot be linked together (ie, one parameter cannot depend on another one).

  2. If a widget returns multiple numerical values (like panel.widgets.slider.RangeSlider or ipywidgets.widgets.widget_float.FloatRangeSlider), then a corresponding number of symbols must be provided.

Here follows a couple of examples. If imodule="panel":

import panel as pn
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: pn.widgets.FloatSlider(value=1, start=0, end=5), # same slider as above
    (c, d): pn.widgets.RangeSlider(value=(-1, 1), start=-3, end=3, step=0.1)
}

Or with imodule="ipywidgets":

import ipywidgets as w
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: w.FloatSlider(value=1, min=0, max=5), # same slider as above
    (c, d): w.FloatRangeSlider(value=(-1, 1), min=-3, max=3, step=0.1)
}

When instantiating a data series directly, params must be a dictionary mapping symbols to numerical values.

Let series be any data series. Then series.params returns a dictionary mapping symbols to numerical values.

polar_axisbool

If True, the backend will attempt to use polar axis, otherwise it uses cartesian axis. This is only supported for 2D plots. Default value: False.

rendering_kwdict

A dictionary of keyword arguments to be passed to the renderers in order to further customize the appearance of the surface. Here are some useful links for the supported plotting libraries:

show_in_legendbool

Toggle the visibility of the data series on the legend. Default value: True.

size

Set the size of the plot, (width, height). For Matplotlib, the size is measured in inches. For Bokeh, Plotly and K3D-Jupyter, the size is in pixel.

sum_boundint

When plotting sums, the expression will be pre-processed in order to replace lower/upper bounds set to +/- infinity with this +/- numerical value. Note: the higher this number, the slower the evaluation, but the more accurate the plot. It must be: 0 ≤ sum_bound < ∞. Default value: 1000.

surface_color

For back-compatibility with old sympy.plotting. Use rendering_kw in order to fully customize the appearance of the surface.

themestr

Theme to be used to style the figure. Depending on the backend being used, several themes may be available.

title

Title of the plot. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

txcallable

Numerical transformation function to be applied to the data on the x-axis.

tycallable

Numerical transformation function to be applied to the data on the y-axis.

tzcallable

Numerical transformation function to be applied to the data on the z-axis.

update_eventbool

If True and the backend supports such functionality, events like drag and zoom will trigger a recompute of the data series within the new axis limits. Default value: False.

use_cmbool

Toggle the use of a colormap. By default, some series might use a colormap to display the necessary data. Setting this attribute to False will inform the associated renderer to use solid color. Related parameters: color_func. Default value: False.

use_latexbool

Turn on/off the rendering of latex labels. If the backend doesn’t support latex, it will render the string representations instead. Default value: True.

x_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the x-axis.

xlabel

Label of the x-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

xlim

Limit the figure’s x-axis to the specified range. The tuple must be in the form (min_val, max_val).

xscaleNoneType, str

If the backend supports it, the x-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

y_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the y-axis.

ylabel

Label of the y-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

ylim

Limit the figure’s y-axis to the specified range. The tuple must be in the form (min_val, max_val).

yscaleNoneType, str

If the backend supports it, the y-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

zlabel

Label of the z-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

zlim

Limit the figure’s z-axis to the specified range. The tuple must be in the form (min_val, max_val).

zscaleNoneType, str

If the backend supports it, the z-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

Examples

>>> from sympy import symbols, cos, sin, pi, Ynm, re, lambdify
>>> from spb import plot3d_spherical
>>> theta, phi = symbols('theta phi')

(Source code)

Sphere cap:

>>> plot3d_spherical(1, (theta, 0, 0.7 * pi), (phi, 0, 1.8 * pi))
Plot object containing:
[0]: parametric cartesian surface: (sin(theta)*cos(phi), sin(phi)*sin(theta), cos(theta)) for theta over (0, 0.7*pi) and phi over (0, 1.8*pi)

(Source code, png)

../../_images/functions_3d-23.png

Plot real spherical harmonics, highlighting the regions in which the real part is positive and negative, using Plotly:

from sympy import symbols, sin, pi, Ynm, re, lambdify
from spb import plot3d_spherical, PB
theta, phi = symbols('theta phi')
r = re(Ynm(3, 3, theta, phi).expand(func=True).rewrite(sin).expand())
plot3d_spherical(
    abs(r), (theta, 0, pi), (phi, 0, 2 * pi), "radius",
    use_cm=True, n2=200, backend=PB,
    color_func=lambdify([theta, phi], r))

(Source code, png)

Multiple surfaces with wireframe lines, using Plotly. Note that activating the wireframe option might add a considerable overhead during the plot’s creation.

from sympy import symbols, sin, pi
from spb import plot3d_spherical, PB
theta, phi = symbols('theta phi')
r1 = 1
r2 = 1.5 + sin(5 * phi) * sin(10 * theta) / 10
plot3d_spherical(r1, r2, (theta, 0, pi / 2), (phi, 0.35 * pi, 2 * pi),
    wireframe=True, wf_n2=25, backend=PB, label=["r1", "r2"])

(Source code, png)

Interactive-widget plot of real spherical harmonics, highlighting the regions in which the real part is positive and negative. Note that the plot’s creation and update might be slow and that it must be m < n at all times. Refer to the interactive sub-module documentation to learn more about the params dictionary.

from sympy import *
from spb import *
import panel as pn
n, m = symbols("n, m")
phi, theta = symbols("phi, theta", real=True)
r = re(Ynm(n, m, theta, phi).expand(func=True).rewrite(sin).expand())
plot3d_spherical(
    abs(r), (theta, 0, pi), (phi, 0, 2*pi),
    params = {
        n: pn.widgets.IntInput(value=2, name="n"),
        m: pn.widgets.IntInput(value=0, name="m"),
    },
    force_real_eval=True,
    use_cm=True, color_func=r,
    backend=KB, imodule="panel")

(Source code, small.png)

../../_images/functions_3d-26.small.png
spb.plot_functions.functions_3d.plot3d_revolution(curve, range_t, range_phi=None, axis=(0, 0), parallel_axis='z', show_curve=False, curve_kw={}, **kwargs)[source]

Generate a surface of revolution by rotating a curve around an axis of rotation.

Refer to surface_revolution() for a full list of keyword arguments to customize the appearances of surfaces.

Refer to graphics() for a full list of keyword arguments to customize the appearances of the figure (title, axis labels, …).

Parameters:
curveExpr, list ortuple of 2 or 3 elements

The curve to be revolved, which can be either:

  • a symbolic expression

  • a 2-tuple representing a parametric curve in 2D space

  • a 3-tuple representing a parametric curve in 3D space

range_ttuple

A 3-tuple (symbol, min, max) denoting the range of the parameter of the curve.

range_phituple

A 3-tuple (symbol, min, max) denoting the range of the azimuthal angle where the curve will be revolved. Default to (phi, 0, 2*pi).

axistuple

A 2-tuple (coord1, coord2) that specifies the position of the rotation axis. Depending on the value of parallel_axis:

  • "x": the rotation axis intersects the YZ plane at (coord1, coord2).

  • "y": the rotation axis intersects the XZ plane at (coord1, coord2).

  • "z": the rotation axis intersects the XY plane at (coord1, coord2).

Default to (0, 0).

parallel_axisstr

Specify the axis parallel to the axis of rotation. Must be one of the following options: “x”, “y” or “z”. Default to “z”.

show_curvebool

Add the initial curve to the plot. Default to False.

labelstr

Set the label associated to this series, which will be eventually shown on the legend or colorbar.

aspectstr, tuple, list, dict

Set the aspect ratio.

Possible values for Matplotlib (only works for a 2D plot):

  • "auto": Matplotlib will fit the plot in the vibile area.

  • "equal": sets equal spacing.

  • tuple containing 2 float numbers, from which the aspect ratio is computed. This only works for 2D plots.

Possible values for Plotly:

  • "equal": sets equal spacing on the axis of a 2D plot.

  • For 3D plots:

    • "cube": fix the ratio to be a cube

    • "data": draw axes in proportion of their ranges

    • "auto": automatically produce something that is well proportioned using ‘data’ as the default.

    • manually set the aspect ratio by providing a dictionary. For example: dict(x=1, y=1, z=2) forces the z-axis to appear twice as big as the other two.

Possible values for Bokeh:

  • "equal": sets equal spacing.

ax

An existing Matplotlib’s Axes over which the symbolic expressions will be plotted.

axis_centerstr, tuple

Set the location of the intersection between the horizontal and vertical axis in a 2D plot. It only works with Matplotlib and it can receive the following values:

  • None: traditional layout, with the horizontal axis fixed on the bottom and the vertical axis fixed on the left. This is the default value.

  • a tuple (x, y) specifying the exact intersection point.

  • 'center': center of the current plot area.

  • 'auto': the intersection point is automatically computed.

camera

Set the camera position for 3D plots.

For Matplotlib, it can be a dictionary of keyword arguments that will be passed to the Axes3D.view_init method. Refer to the following link for more information: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html#mpl_toolkits.mplot3d.axes3d.Axes3D.view_init

For Plotly, it can be a dictionary of keyword arguments that will be passed to the layout’s scene_camera. Refer to the following link for more information: https://plotly.com/python/3d-camera-controls/

For K3D-Jupyter, it is list of 9 numbers, namely:

  • x_cam, y_cam, z_cam: the position of the camera in the scene

  • x_tar, y_tar, z_tar: the position of the target of the camera

  • x_up, y_up, z_up: components of the up vector

color_func

Define the surface color mapping when use_cm=True. It can either be:

  • None: the default value (color mapping according to the z coordinate).

  • A numerical function supporting vectorization. The arity can be:

    • 1 argument: f(u), where u is the first parameter.

    • 2 arguments: f(u, v) where u, v are the parameters.

    • 3 arguments: f(x, y, z) where x, y, z are the coordinates of the points.

    • 5 arguments: f(x, y, z, u, v).

  • A symbolic expression having at most as many free symbols as expr_x or expr_y or expr_z.

colorbarbool

Toggle the visibility of the colorbar associated to the current data series. Note that a colorbar is only visible if use_cm=True and color_func is not None. Default value: True.

colorbar_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values on the colorbar at each multiple of a specified quantity. This only works when use_cm=True.

colorlooplist, tuple

List of colors to be used in line plots or solid color surfaces.

colormapslist, tuple

List of color maps to render surfaces.

curve_kwdict

A dictionary of options that will be passed to plot3d_parametric_line if show_curve=True in order to customize the appearance of the initial curve. Refer to its documentation for more information.

cyclic_colormapslist, tuple

List of cyclic color maps to render complex series (the phase/argument ranges over [-pi, pi]).

fig

Get or set the figure where to plot into.

force_real_evalbool

By default, numerical evaluation is performed over complex numbers, which is slower but produces correct results. However, when the symbolic expression is converted to a numerical function with lambdify, the resulting function may not like to be evaluated over complex numbers. In such cases, forcing the evaluation to be performed over real numbers might be a good choice. The plotting module should be able to detect such occurences and automatically activate this option. If that is not the case, or evaluation performance is of paramount importance, set this parameter to True, but be aware that it might produce wrong results. Default value: False.

gridbool, dict

Toggle the visibility of major grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

hookslist

List of functions expecting one argument, the current plot object, which allows users to further customize the appearance of the plot before it is shown on the screen. The hooks are executed:

  1. after the figure has been initialized and populated with numerical data.

  2. after the existing renderers update the visualization because the user interacted with some widget.

Note: let p be the plot object. Then, the user can access the figure with p.fig. In case of spb.backends.matplotlib.MatplotlibBackend, the user can also retrieve the axes in which data was added with p.ax.

legendbool

Toggle the visibility of the legend. If None, the backend will automatically determine if it is appropriate to show it. Default value: None.

minor_gridbool, dict

Toggle the visibility of minor grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

modules

Specify the evaluation modules to be used by lambdify. If not specified, the evaluation will be done with NumPy/SciPy.

n1int

Number of discretization points along the first parameter to be used in the evaluation. Related parameters: xscale. It must be: 2 ≤ n1 < ∞. Default value: 100.

n2int

Number of discretization points along the second parameter to be used in the evaluation. Related parameters: yscale. It must be: 2 ≤ n2 < ∞. Default value: 100.

only_integersbool

Discretize the domain using only integer numbers. When this parameter is True, the number of discretization points is choosen by the algorithm. Default value: False.

paramsdict, optional

A dictionary mapping symbols to parameters. If provided, this dictionary enables the interactive-widgets plot.

When calling a plotting function, the parameter can be specified with:

  • a widget from the ipywidgets module.

  • a widget from the panel module.

  • a tuple of the form:

    (default, min, max, N, tick_format, label, spacing), which will instantiate a ipywidgets.widgets.widget_float.FloatSlider or a ipywidgets.widgets.widget_float.FloatLogSlider, depending on the spacing strategy. In particular:

    • default, min, maxfloat

      Default value, minimum value and maximum value of the slider, respectively. Must be finite numbers. The order of these 3 numbers is not important: the module will figure it out which is what.

    • Nint, optional

      Number of steps of the slider.

    • tick_formatstr or None, optional

      Provide a formatter for the tick value of the slider. Default to ".2f".

    • label: str, optional

      Custom text associated to the slider.

    • spacingstr, optional

      Specify the discretization spacing. Default to "linear", can be changed to "log".

Notes:

  1. parameters cannot be linked together (ie, one parameter cannot depend on another one).

  2. If a widget returns multiple numerical values (like panel.widgets.slider.RangeSlider or ipywidgets.widgets.widget_float.FloatRangeSlider), then a corresponding number of symbols must be provided.

Here follows a couple of examples. If imodule="panel":

import panel as pn
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: pn.widgets.FloatSlider(value=1, start=0, end=5), # same slider as above
    (c, d): pn.widgets.RangeSlider(value=(-1, 1), start=-3, end=3, step=0.1)
}

Or with imodule="ipywidgets":

import ipywidgets as w
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: w.FloatSlider(value=1, min=0, max=5), # same slider as above
    (c, d): w.FloatRangeSlider(value=(-1, 1), min=-3, max=3, step=0.1)
}

When instantiating a data series directly, params must be a dictionary mapping symbols to numerical values.

Let series be any data series. Then series.params returns a dictionary mapping symbols to numerical values.

polar_axisbool

If True, the backend will attempt to use polar axis, otherwise it uses cartesian axis. This is only supported for 2D plots. Default value: False.

rendering_kwdict

A dictionary of keyword arguments to be passed to the renderers in order to further customize the appearance of the surface. Here are some useful links for the supported plotting libraries:

show_in_legendbool

Toggle the visibility of the data series on the legend. Default value: True.

size

Set the size of the plot, (width, height). For Matplotlib, the size is measured in inches. For Bokeh, Plotly and K3D-Jupyter, the size is in pixel.

sum_boundint

When plotting sums, the expression will be pre-processed in order to replace lower/upper bounds set to +/- infinity with this +/- numerical value. Note: the higher this number, the slower the evaluation, but the more accurate the plot. It must be: 0 ≤ sum_bound < ∞. Default value: 1000.

surface_color

For back-compatibility with old sympy.plotting. Use rendering_kw in order to fully customize the appearance of the surface.

themestr

Theme to be used to style the figure. Depending on the backend being used, several themes may be available.

title

Title of the plot. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

txcallable

Numerical transformation function to be applied to the data on the x-axis.

tycallable

Numerical transformation function to be applied to the data on the y-axis.

tzcallable

Numerical transformation function to be applied to the data on the z-axis.

update_eventbool

If True and the backend supports such functionality, events like drag and zoom will trigger a recompute of the data series within the new axis limits. Default value: False.

use_cmbool

Toggle the use of a colormap. By default, some series might use a colormap to display the necessary data. Setting this attribute to False will inform the associated renderer to use solid color. Related parameters: color_func. Default value: False.

use_latexbool

Turn on/off the rendering of latex labels. If the backend doesn’t support latex, it will render the string representations instead. Default value: True.

x_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the x-axis.

xlabel

Label of the x-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

xlim

Limit the figure’s x-axis to the specified range. The tuple must be in the form (min_val, max_val).

xscaleNoneType, str

If the backend supports it, the x-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

y_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the y-axis.

ylabel

Label of the y-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

ylim

Limit the figure’s y-axis to the specified range. The tuple must be in the form (min_val, max_val).

yscaleNoneType, str

If the backend supports it, the y-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

zlabel

Label of the z-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

zlim

Limit the figure’s z-axis to the specified range. The tuple must be in the form (min_val, max_val).

zscaleNoneType, str

If the backend supports it, the z-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

Examples

>>> from sympy import symbols, cos, sin, pi
>>> from spb import plot3d_revolution
>>> t, phi = symbols('t phi')

(Source code)

Revolve a function around the z axis:

>>> plot3d_revolution(
...     cos(t), (t, 0, pi),
...     # use a color map on the surface to indicate the azimuthal angle
...     use_cm=True, color_func=lambda t, phi: phi,
...     rendering_kw={"alpha": 0.6, "cmap": "twilight"},
...     # indicates the azimuthal angle on the colorbar label
...     label="$\phi$ [rad]",
...     show_curve=True,
...     # this dictionary will be passes to plot3d_parametric_line in
...     # order to draw the initial curve
...     curve_kw=dict(rendering_kw={"color": "r", "label": "cos(t)"}),
...     # activate the wireframe to visualize the parameterization
...     wireframe=True, wf_n1=15, wf_n2=15,
...     wf_rendering_kw={"lw": 0.5, "alpha": 0.75})  

(Source code, png)

../../_images/functions_3d-28.png

Revolve the same function around an axis parallel to the x axis, using Plotly:

from sympy import symbols, cos, sin, pi
from spb import plot3d_revolution, PB
t, phi = symbols('t phi')
plot3d_revolution(
    cos(t), (t, 0, pi), parallel_axis="x", axis=(1, 0),
    backend=PB, use_cm=True, color_func=lambda t, phi: phi,
    rendering_kw={"colorscale": "twilight"},
    label="phi [rad]",
    show_curve=True,
    curve_kw=dict(rendering_kw={"line": {"color": "red", "width": 8},
        "name": "cos(t)"}),
    wireframe=True, wf_n1=15, wf_n2=15,
    wf_rendering_kw={"line_width": 1})

(Source code, png)

Revolve a 2D parametric circle around the z axis:

from sympy import *
from spb import *
t = symbols("t")
circle = (3 + cos(t), sin(t))
plot3d_revolution(circle, (t, 0, 2 * pi),
    backend=KB, show_curve=True,
    rendering_kw={"opacity": 0.65},
    curve_kw={"rendering_kw": {"width": 0.05}})

(Source code, small.png)

../../_images/functions_3d-30.small.png

Revolve a 3D parametric curve around the z axis for a given azimuthal angle, using Plotly:

plot3d_revolution(
    (cos(t), sin(t), t), (t, 0, 2*pi), (phi, 0, pi),
    use_cm=True, color_func=lambda t, phi: t, label="t [rad]",
    show_curve=True, backend=PB, aspect="cube",
    wireframe=True, wf_n1=2, wf_n2=5)

(Source code, png)

Interactive-widget plot of a goblet. Refer to the interactive sub-module documentation to learn more about the params dictionary. This plot illustrates:

  • the use of prange (parametric plotting range).

  • the use of the params dictionary to specify sliders in their basic form: (default, min, max).

from sympy import *
from spb import *
t, phi, u, v, w = symbols("t phi u v w")
plot3d_revolution(
    (t, cos(u * t), t**2), prange(t, 0, v), prange(phi, 0, w*pi),
    axis=(1, 0.2),
    params={
        u: (2.5, 0, 6),
        v: (2, 0, 3),
        w: (2, 0, 2)
    }, n=50, backend=KB, force_real_eval=True,
    wireframe=True, wf_n1=15, wf_n2=15,
    wf_rendering_kw={"width": 0.004},
    show_curve=True, curve_kw={"rendering_kw": {"width": 0.025}})

(Source code, small.png)

../../_images/functions_3d-32.small.png
spb.plot_functions.functions_3d.plot3d_implicit(*args, **kwargs)[source]

Plots an isosurface of a function.

Typical usage examples are in the followings:

  • Plotting a single expression:

    plot3d_implicit(
       expr, range_x, range_y, range_z, rendering_kw [optional], **kwargs)
    
  • Plotting a multiple expression over the same range:

    plot3d_implicit(
       expr1, expr2, range_x, range_y, range_z,
       rendering_kw [optional], **kwargs)`
    
  • Plotting a multiple expression with different range and rendering options:

    plot3d_implicit(
       (expr1, range_x1, range_y1, range_z1, rendering_kw1 [opt]),
       (expr2, range_x2, range_y2, range_z2, rendering_kw2 [opt]),
       **kwargs)`
    
Parameters:
aspectstr, tuple, list, dict

Set the aspect ratio.

Possible values for Matplotlib (only works for a 2D plot):

  • "auto": Matplotlib will fit the plot in the vibile area.

  • "equal": sets equal spacing.

  • tuple containing 2 float numbers, from which the aspect ratio is computed. This only works for 2D plots.

Possible values for Plotly:

  • "equal": sets equal spacing on the axis of a 2D plot.

  • For 3D plots:

    • "cube": fix the ratio to be a cube

    • "data": draw axes in proportion of their ranges

    • "auto": automatically produce something that is well proportioned using ‘data’ as the default.

    • manually set the aspect ratio by providing a dictionary. For example: dict(x=1, y=1, z=2) forces the z-axis to appear twice as big as the other two.

Possible values for Bokeh:

  • "equal": sets equal spacing.

ax

An existing Matplotlib’s Axes over which the symbolic expressions will be plotted.

axisbool

Show the axis in the figure. Default value: True.

axis_centerstr, tuple

Set the location of the intersection between the horizontal and vertical axis in a 2D plot. It only works with Matplotlib and it can receive the following values:

  • None: traditional layout, with the horizontal axis fixed on the bottom and the vertical axis fixed on the left. This is the default value.

  • a tuple (x, y) specifying the exact intersection point.

  • 'center': center of the current plot area.

  • 'auto': the intersection point is automatically computed.

camera

Set the camera position for 3D plots.

For Matplotlib, it can be a dictionary of keyword arguments that will be passed to the Axes3D.view_init method. Refer to the following link for more information: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html#mpl_toolkits.mplot3d.axes3d.Axes3D.view_init

For Plotly, it can be a dictionary of keyword arguments that will be passed to the layout’s scene_camera. Refer to the following link for more information: https://plotly.com/python/3d-camera-controls/

For K3D-Jupyter, it is list of 9 numbers, namely:

  • x_cam, y_cam, z_cam: the position of the camera in the scene

  • x_tar, y_tar, z_tar: the position of the target of the camera

  • x_up, y_up, z_up: components of the up vector

colorlooplist, tuple

List of colors to be used in line plots or solid color surfaces.

colormapslist, tuple

List of color maps to render surfaces.

cyclic_colormapslist, tuple

List of cyclic color maps to render complex series (the phase/argument ranges over [-pi, pi]).

fig

Get or set the figure where to plot into.

gridbool, dict

Toggle the visibility of major grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

hookslist

List of functions expecting one argument, the current plot object, which allows users to further customize the appearance of the plot before it is shown on the screen. The hooks are executed:

  1. after the figure has been initialized and populated with numerical data.

  2. after the existing renderers update the visualization because the user interacted with some widget.

Note: let p be the plot object. Then, the user can access the figure with p.fig. In case of spb.backends.matplotlib.MatplotlibBackend, the user can also retrieve the axes in which data was added with p.ax.

legendbool

Toggle the visibility of the legend. If None, the backend will automatically determine if it is appropriate to show it. Default value: None.

minor_gridbool, dict

Toggle the visibility of minor grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

paramsdict, optional

A dictionary mapping symbols to parameters. If provided, this dictionary enables the interactive-widgets plot.

When calling a plotting function, the parameter can be specified with:

  • a widget from the ipywidgets module.

  • a widget from the panel module.

  • a tuple of the form:

    (default, min, max, N, tick_format, label, spacing), which will instantiate a ipywidgets.widgets.widget_float.FloatSlider or a ipywidgets.widgets.widget_float.FloatLogSlider, depending on the spacing strategy. In particular:

    • default, min, maxfloat

      Default value, minimum value and maximum value of the slider, respectively. Must be finite numbers. The order of these 3 numbers is not important: the module will figure it out which is what.

    • Nint, optional

      Number of steps of the slider.

    • tick_formatstr or None, optional

      Provide a formatter for the tick value of the slider. Default to ".2f".

    • label: str, optional

      Custom text associated to the slider.

    • spacingstr, optional

      Specify the discretization spacing. Default to "linear", can be changed to "log".

Notes:

  1. parameters cannot be linked together (ie, one parameter cannot depend on another one).

  2. If a widget returns multiple numerical values (like panel.widgets.slider.RangeSlider or ipywidgets.widgets.widget_float.FloatRangeSlider), then a corresponding number of symbols must be provided.

Here follows a couple of examples. If imodule="panel":

import panel as pn
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: pn.widgets.FloatSlider(value=1, start=0, end=5), # same slider as above
    (c, d): pn.widgets.RangeSlider(value=(-1, 1), start=-3, end=3, step=0.1)
}

Or with imodule="ipywidgets":

import ipywidgets as w
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: w.FloatSlider(value=1, min=0, max=5), # same slider as above
    (c, d): w.FloatRangeSlider(value=(-1, 1), min=-3, max=3, step=0.1)
}

When instantiating a data series directly, params must be a dictionary mapping symbols to numerical values.

Let series be any data series. Then series.params returns a dictionary mapping symbols to numerical values.

polar_axisbool

If True, the backend will attempt to use polar axis, otherwise it uses cartesian axis. This is only supported for 2D plots. Default value: False.

size

Set the size of the plot, (width, height). For Matplotlib, the size is measured in inches. For Bokeh, Plotly and K3D-Jupyter, the size is in pixel.

themestr

Theme to be used to style the figure. Depending on the backend being used, several themes may be available.

title

Title of the plot. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

update_eventbool

If True and the backend supports such functionality, events like drag and zoom will trigger a recompute of the data series within the new axis limits. Default value: False.

use_latexbool

Turn on/off the rendering of latex labels. If the backend doesn’t support latex, it will render the string representations instead. Default value: True.

x_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the x-axis.

xlabel

Label of the x-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

xlim

Limit the figure’s x-axis to the specified range. The tuple must be in the form (min_val, max_val).

xscaleNoneType, str

If the backend supports it, the x-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

y_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the y-axis.

ylabel

Label of the y-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

ylim

Limit the figure’s y-axis to the specified range. The tuple must be in the form (min_val, max_val).

yscaleNoneType, str

If the backend supports it, the y-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

zlabel

Label of the z-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

zlim

Limit the figure’s z-axis to the specified range. The tuple must be in the form (min_val, max_val).

zscaleNoneType, str

If the backend supports it, the z-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

Notes

  1. the number of discretization points is crucial as the algorithm will discretize a volume. A high number of discretization points creates a smoother mesh, at the cost of a much higher memory consumption and slower computation.

  2. Only PlotlyBackend and K3DBackend support 3D implicit plotting.

  3. To plot f(x, y, z) = c either write expr = f(x, y, z) - c or pass the appropriate keyword to rendering_kw. Read the backends documentation to find out the available options.

Examples

from sympy import symbols
from spb import plot3d_implicit, PB, KB
x, y, z = symbols('x, y, z')
plot3d_implicit(
    x**2 + y**3 - z**2, (x, -2, 2), (y, -2, 2), (z, -2, 2), backend=PB)

(Source code, png)

plot3d_implicit(
    x**4 + y**4 + z**4 - (x**2 + y**2 + z**2 - 0.3),
    (x, -2, 2), (y, -2, 2), (z, -2, 2), backend=PB)

(Source code, png)

Visualize the isocontours from isomin=0 to isomax=2 by providing a rendering_kw dictionary:

plot3d_implicit(
    1/x**2 - 1/y**2 + 1/z**2, (x, -2, 2), (y, -2, 2), (z, -2, 2),
    {
        "isomin": 0, "isomax": 2,
        "colorscale":"aggrnyl", "showscale":True
    },
    backend=PB
)

(Source code, png)

spb.plot_functions.functions_3d.plot3d_list(*args, **kwargs)[source]

Plots lists of coordinates (ie, lists of numbers) in 3D space.

Typical usage examples are in the followings:

  • Plotting coordinates of a single function:

    plot3d_list(x, y, **kwargs)
    
  • Plotting coordinates of multiple functions, adding custom labels and rendering options:

    plot3d_list(
       (x1, y1, z1, label1 [opt], rendering_kw1 [opt]),
       (x2, y2, z1, label2 [opt], rendering_kw2 [opt]),
       ..., **kwargs)
    
Parameters:
aspectstr, tuple, list, dict

Set the aspect ratio.

Possible values for Matplotlib (only works for a 2D plot):

  • "auto": Matplotlib will fit the plot in the vibile area.

  • "equal": sets equal spacing.

  • tuple containing 2 float numbers, from which the aspect ratio is computed. This only works for 2D plots.

Possible values for Plotly:

  • "equal": sets equal spacing on the axis of a 2D plot.

  • For 3D plots:

    • "cube": fix the ratio to be a cube

    • "data": draw axes in proportion of their ranges

    • "auto": automatically produce something that is well proportioned using ‘data’ as the default.

    • manually set the aspect ratio by providing a dictionary. For example: dict(x=1, y=1, z=2) forces the z-axis to appear twice as big as the other two.

Possible values for Bokeh:

  • "equal": sets equal spacing.

ax

An existing Matplotlib’s Axes over which the symbolic expressions will be plotted.

axisbool

Show the axis in the figure. Default value: True.

axis_centerstr, tuple

Set the location of the intersection between the horizontal and vertical axis in a 2D plot. It only works with Matplotlib and it can receive the following values:

  • None: traditional layout, with the horizontal axis fixed on the bottom and the vertical axis fixed on the left. This is the default value.

  • a tuple (x, y) specifying the exact intersection point.

  • 'center': center of the current plot area.

  • 'auto': the intersection point is automatically computed.

camera

Set the camera position for 3D plots.

For Matplotlib, it can be a dictionary of keyword arguments that will be passed to the Axes3D.view_init method. Refer to the following link for more information: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html#mpl_toolkits.mplot3d.axes3d.Axes3D.view_init

For Plotly, it can be a dictionary of keyword arguments that will be passed to the layout’s scene_camera. Refer to the following link for more information: https://plotly.com/python/3d-camera-controls/

For K3D-Jupyter, it is list of 9 numbers, namely:

  • x_cam, y_cam, z_cam: the position of the camera in the scene

  • x_tar, y_tar, z_tar: the position of the target of the camera

  • x_up, y_up, z_up: components of the up vector

colorlooplist, tuple

List of colors to be used in line plots or solid color surfaces.

colormapslist, tuple

List of color maps to render surfaces.

cyclic_colormapslist, tuple

List of cyclic color maps to render complex series (the phase/argument ranges over [-pi, pi]).

fig

Get or set the figure where to plot into.

gridbool, dict

Toggle the visibility of major grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

hookslist

List of functions expecting one argument, the current plot object, which allows users to further customize the appearance of the plot before it is shown on the screen. The hooks are executed:

  1. after the figure has been initialized and populated with numerical data.

  2. after the existing renderers update the visualization because the user interacted with some widget.

Note: let p be the plot object. Then, the user can access the figure with p.fig. In case of spb.backends.matplotlib.MatplotlibBackend, the user can also retrieve the axes in which data was added with p.ax.

legendbool

Toggle the visibility of the legend. If None, the backend will automatically determine if it is appropriate to show it. Default value: None.

minor_gridbool, dict

Toggle the visibility of minor grid lines. A dictionary of keyword arguments can be passed to customized the appearance of the grid lines:

paramsdict, optional

A dictionary mapping symbols to parameters. If provided, this dictionary enables the interactive-widgets plot.

When calling a plotting function, the parameter can be specified with:

  • a widget from the ipywidgets module.

  • a widget from the panel module.

  • a tuple of the form:

    (default, min, max, N, tick_format, label, spacing), which will instantiate a ipywidgets.widgets.widget_float.FloatSlider or a ipywidgets.widgets.widget_float.FloatLogSlider, depending on the spacing strategy. In particular:

    • default, min, maxfloat

      Default value, minimum value and maximum value of the slider, respectively. Must be finite numbers. The order of these 3 numbers is not important: the module will figure it out which is what.

    • Nint, optional

      Number of steps of the slider.

    • tick_formatstr or None, optional

      Provide a formatter for the tick value of the slider. Default to ".2f".

    • label: str, optional

      Custom text associated to the slider.

    • spacingstr, optional

      Specify the discretization spacing. Default to "linear", can be changed to "log".

Notes:

  1. parameters cannot be linked together (ie, one parameter cannot depend on another one).

  2. If a widget returns multiple numerical values (like panel.widgets.slider.RangeSlider or ipywidgets.widgets.widget_float.FloatRangeSlider), then a corresponding number of symbols must be provided.

Here follows a couple of examples. If imodule="panel":

import panel as pn
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: pn.widgets.FloatSlider(value=1, start=0, end=5), # same slider as above
    (c, d): pn.widgets.RangeSlider(value=(-1, 1), start=-3, end=3, step=0.1)
}

Or with imodule="ipywidgets":

import ipywidgets as w
params = {
    a: (1, 0, 5), # slider from 0 to 5, with default value of 1
    b: w.FloatSlider(value=1, min=0, max=5), # same slider as above
    (c, d): w.FloatRangeSlider(value=(-1, 1), min=-3, max=3, step=0.1)
}

When instantiating a data series directly, params must be a dictionary mapping symbols to numerical values.

Let series be any data series. Then series.params returns a dictionary mapping symbols to numerical values.

polar_axisbool

If True, the backend will attempt to use polar axis, otherwise it uses cartesian axis. This is only supported for 2D plots. Default value: False.

size

Set the size of the plot, (width, height). For Matplotlib, the size is measured in inches. For Bokeh, Plotly and K3D-Jupyter, the size is in pixel.

themestr

Theme to be used to style the figure. Depending on the backend being used, several themes may be available.

title

Title of the plot. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

update_eventbool

If True and the backend supports such functionality, events like drag and zoom will trigger a recompute of the data series within the new axis limits. Default value: False.

use_latexbool

Turn on/off the rendering of latex labels. If the backend doesn’t support latex, it will render the string representations instead. Default value: True.

x_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the x-axis.

xlabel

Label of the x-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

xlim

Limit the figure’s x-axis to the specified range. The tuple must be in the form (min_val, max_val).

xscaleNoneType, str

If the backend supports it, the x-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

y_ticks_formattertick_formatter_multiples_of

An object of type tick_formatter_multiples_of which will be used to place tick values at each multiple of a specified quantity, along the y-axis.

ylabel

Label of the y-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

ylim

Limit the figure’s y-axis to the specified range. The tuple must be in the form (min_val, max_val).

yscaleNoneType, str

If the backend supports it, the y-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

zlabel

Label of the z-axis. It can be:

  • a string.

  • a callable receiving a single argument, use_latex, which must return a string.

  • a tuple of the form (format_str, symbol 1, symbol 2, etc.), which creates an output string when parameters symbol 1, symbol 2, etc. receive numerical values from the widgets. This operation mode only works when creating interactive data series (ie, specifying the params dictionary).

zlim

Limit the figure’s z-axis to the specified range. The tuple must be in the form (min_val, max_val).

zscaleNoneType, str

If the backend supports it, the z-direction will use the specified scale. Note that none of the backends support logarithmic scale for 3D plots. Possible options: [‘linear’, ‘log’, None] Default value: ‘linear’.

Examples

>>> from sympy import *
>>> from spb import plot3d_list
>>> import numpy as np

(Source code)

Plot the coordinates of a single function:

>>> z = np.linspace(0, 6*np.pi, 100)
>>> x = z * np.cos(z)
>>> y = z * np.sin(z)
>>> plot3d_list(x, y, z)
Plot object containing:
[0]: 3D list plot

(Source code, png)

../../_images/functions_3d-37.png

Plotting multiple functions with custom rendering keywords:

>>> plot3d_list(
...     (x, y, z, "A"),
...     (x, y, -z, "B", {"linestyle": "--"}))
Plot object containing:
[0]: 3D list plot
[1]: 3D list plot

(Source code, png)

../../_images/functions_3d-38.png

Interactive-widget plot of a dot following a path. Refer to the interactive sub-module documentation to learn more about the params dictionary.

from sympy import *
from spb import *
import numpy as np
t = symbols("t")
z = np.linspace(0, 6*np.pi, 100)
x = z * np.cos(z)
y = z * np.sin(z)
p1 = plot3d_list(x, y, z,
    show=False, is_scatter=False)
p2 = plot3d_list(
    [t * cos(t)], [t * sin(t)], [t],
    params={t: (3*pi, 0, 6*pi)},
    backend=PB, show=False, is_scatter=True,
    imodule="panel")
(p2 + p1).show()

(Source code, small.png)

../../_images/functions_3d-39.small.png