# plotting sympy results in python

• Last Update :
• Techknowledgy :
>>> from sympy
import symbols
>>>
from sympy.plotting
import plot
>>>
x = symbols('x') >>>
p1 = plot(x * x, show = False) >>>
p2 = plot(x, show = False) >>>
p1.append(p2[0]) >>>
p1
Plot object containing: [0]: cartesian line: x ** 2
for x over(-10.0, 10.0)[1]: cartesian line: x
for x over(-10.0, 10.0) >>>
p1.show()
>>> from sympy
import symbols
>>>
from sympy.plotting
import plot
>>>
x = symbols('x') >>>
p1 = plot(x ** 2, show = False) >>>
p2 = plot(x, -x, show = False) >>>
p1.extend(p2) >>>
p1
Plot object containing: [0]: cartesian line: x ** 2
for x over(-10.0, 10.0)[1]: cartesian line: x
for x over(-10.0, 10.0)[2]: cartesian line: -x
for x over(-10.0, 10.0) >>>
p1.show()
>>> from sympy
import symbols
>>>
from sympy.plotting
import plot
>>>
x = symbols('x')
>>> plot(x ** 2, (x, -5, 5))
Plot object containing: [0]: cartesian line: x ** 2
for x over(-5.0, 5.0)
>>> plot(x, x ** 2, x ** 3, (x, -5, 5))
Plot object containing: [0]: cartesian line: x
for x over(-5.0, 5.0)[1]: cartesian line: x ** 2
for x over(-5.0, 5.0)[2]: cartesian line: x ** 3
for x over(-5.0, 5.0)
>>> plot((x ** 2, (x, -6, 6)), (x, (x, -5, 5)))
Plot object containing: [0]: cartesian line: x ** 2
for x over(-6.0, 6.0)[1]: cartesian line: x
for x over(-5.0, 5.0)

Suggestion : 2

SymPy uses Matplotlib library as a backend to render 2-D and 3-D plots of mathematical functions. Ensure that Matplotlib is available in current Python installation. If not, install the same using following command −,The plot() function returns an instance of Plot class. A plot figure may have one or more SymPy expressions. Although it is capable of using Matplotlib as backend, other backends such as texplot, pyglet or Google charts API may also be used.,As in 2D plot, a three dimensional plot can also have multiple plots each with different range.,Plotting support is defined in sympy.plotting module. Following functions are present in plotting module −

SymPy uses Matplotlib library as a backend to render 2-D and 3-D plots of mathematical functions. Ensure that Matplotlib is available in current Python installation. If not, install the same using following command −

pip install matplotlib

The plot() function returns an instance of Plot class. A plot figure may have one or more SymPy expressions. Although it is capable of using Matplotlib as backend, other backends such as texplot, pyglet or Google charts API may also be used.

plot(expr, range, kwargs)

Following example plots values of x2 for each value in range(-10,10) −

>>> from sympy.plotting
import plot
>>>
from sympy
import *
>>>
x = Symbol('x') >>>
plot(x ** 2, line_color = 'red')

You can also specify separate range for each expression.

plot((expr1, range1), (expr2, range2))

Following figure plots sin(x) and cos(x) over different ranges.

>>> plot((sin(x), (x, -2 * pi, 2 * pi)), (cos(x), (x, -pi, pi)))

Suggestion : 3

To use the plotting library we are most comfortable with. The backend can be used as a starting point to plot symbolic expressions; then, we could use the figure object to add numerical (or experimental) results using the commands associated to the specific plotting library.,Originally, the module has been developed with SymPy in mind, however it has evolved to the point where lambda functions can be used instead of symbolic expressions.,the full potential of each backend can be accessed by providing dictionaries containing backend-specific keyword arguments.,In the Python ecosystem there is no perfect plotting library. Each one is great at something and terrible at something else. Supporting multiple backends allows the plotting module to have a greater capability of visualizing different kinds of symbolic expressions.

from sympy
import symbols, sin, cos, pi, latex
from spb
import plot_polar
x = symbols("x")
expr = sin(2 * x) * cos(5 * x) + pi / 2
plot_polar(expr, (x, 0, 2 * pi), ylim = (0, 3), title = "$%s$" % latex(expr))
import numpy as np
from spb
import plot_parametric
plot_parametric(
lambda t: np.sin(3 * t + np.pi / 4), lambda t: np.sin(4 * t),
("t", 0, 2 * pi), "t [rad]", xlabel = "x", ylabel = "y", aspect = "equal")
from sympy
import symbols, cos, pi
from spb
import plot3d, KB
x, y = symbols("x, y")
expr = cos(2 * pi * x * y)
title = r "\text{K3D - Latex Support} \qquad f(x, y) = " + latex(expr)
plot3d(
expr, (x, -2, 2), (y, -2, 2),
use_cm = False, n = 300, title = title,
backend = KB)
from sympy
import symbols, cos, sin, pi, latex
from spb
import plot3d, KB
r, theta = symbols("r, theta")
expr = cos(r) * cos(sin(4 * theta))
plot3d(
expr, expr, (r, 0, 2), (theta, 0, 2 * pi),
n1 = 50, n2 = 200, is_polar = True, grid = False,
title = r "f\left(r, \theta\right) = " + latex(expr), backend = KB)
from sympy
import symbols
from spb
import plot_vector, PB
x, y = symbols("x, y")
expr = Tuple(x ** 2 - y ** 2 - 4, 2 * x * y)
plot_vector(
expr, (x, -5, 5), (y, -5, 5),
backend = PB,
n = 15, quiver_kw = {
"scale": 0.025
},
theme = "plotly_dark",
xlim = (-5, 5), ylim = (-5, 5),
title = r "$\vec{F} = " + latex(expr) + "$")
from sympy
import symbols, Tuple
from spb
import plot_vector, KB
x, y, z = symbols("x, y, z")
expr = Tuple(-y, -z, x)
plot_vector(
expr, (x, -5, 5), (y, -5, 5), (z, -5, 5),
streamlines = True, n = 30,
backend = KB, grid = False,
stream_kw = {
"starts": True,
"npoints": 500
},
title = r "\vec{F}(x, y, z) = " + latex(expr))

Suggestion : 4

We try to make the sources easily understandable, so you can look into the sources and read the doctests, it should be well documented and if you don�t understand something, ask on the mailinglist.,You can find all the decisions archived in the issues, to see rationale for doing this and that.,Sometimes, you need to have a unique symbol, for example as a temporary one in some calculation, which is going to be substituted for something else at the end anyway. This is achieved using Dummy("x"). So, to sum it up:,Whenever you construct an expression, for example Add(x, x), the Add.__new__() is called and it determines what to return. In this case:

a = Symbol("a")
b = Symbol("b")
e = (a + b) ** 2
print e
>>> from sympy import Add
>>> from sympy.abc import x
>>> e = Add(x, x)
>>> e
2*x

>>> type(e)
<class 'sympy.core.mul.Mul'>
>>> from sympy
import Symbol, Dummy
>>>
Symbol("x") == Symbol("x")
True

>>>
Dummy("x") == Dummy("x")
False
[user @localhost]: SYMPY_DEBUG = True. / bin / isympy

Suggestion : 5

How do I use these results to plot a S-shaped curve constrained by these values. Y-axis ranges from 0 to 1. x1,y1 and x2,y2 are 2 points on that curve.,Python – Why is reading lines from stdin much slower in C++ than Python,Python – Does Python have a string ‘contains’ substring method,Python – Manually raising (throwing) an exception in Python

I am using sympy to solve for b1 and b2:

y = x / [x + exp(b1 - b2 * x)]
x1 = 90;
y1 = 0.05 and x2 = 99;
y2 = 0.95

import sympy
b1, b2 = symbols('b1 b2')
solve([Eq(90 * 0.05 + 90 * exp(b1 - (b2 * 90)) - 90, 0.0), Eq(99 * 0.95 + 99 * exp(b1 - (b2 * 99)) - 99, 0.0)], [b1, b2])

>>> {
b1: 29.3930964972769,
b2: 0.327159886574049
}

Using the latest versions of sympy and ipython

In[1]: from sympy
import *

In[2]: x, b1, b2 = symbols("x b1 b2")

In[3]: f = x / (x + exp(b1 - b2 * x))

In[4]: res = {
b1: 29.3930964972769,
b2: 0.327159886574049
}

In[5]: plot(f.subs(res), (x, 0, 100))

Suggestion : 6

Since most of the basic functions, like the ones for initiating a Sympy session on your terminal or for defining a function/variable, will not be covered in here. ,Figure 3: Parametric representation of a circumference centered at the origin of the x and y axes.,At this point, we should be able to see in a separate matplotlib window, the plot of our function; Figure 1 reports the outcome of the example.,In this section we will see firstly how to express an integral of a function in the terminal; as you will see, Sympy allows for a better representation of the function within the terminal.

Sympy allows to solve this task in a very immediate way; the function that is used to this purpose is called diff(), from “differential”. The function diff(), takes as input parameter the function that we want to derivate. In the following code lines, we define a function, “f”, and we calculate its first derivative.

>>> f = 3 * x ** 2 + 4 * x + 5 >>>
diff(f)
6⋅ x + 4

To calculate the second or higher order derivatives of functions with Sympy, it is just sufficient to specify, after the function name, the variable with respect to which we want to make the derivation and the number of times we want to perform the differentiation (i.e. calculating the derivatives). In the following code lines, we calculate the second derivative of “f”, i.e. we differentiate the function twice.

>>> f
2
3⋅ x + 4⋅ x + 5 >>>
diff(f, x, 2)
6

When we are dealing with multi-variable functions, we may be interested in calculating their partial derivatives; to do that, it is sufficient to specify the variable with respect to which we want to differentiate the function. In the following example, the function “g” is a three-variable function (x, y, z); we hence show how to calculate the partial derivatives with respect to each of three variables.

>>> g = 2 * x + 4 * y ** 2 - x * z >>>
diff(g, x)
2 - z >>>
diff(g, y)
8⋅ y
>>>
diff(g, z) -
x

At this stage, we have just expressed the integral that we want to solve, using the mathematical notation. However, what really interests us is how to actually solve the integral. To solve the integral, we use a function called integrate(); the input parameters are still the same; if you just want to solve the integral symbolically, you do not have to specify the integration limits. In the following code lines, we first solve the integral symbolically and then numerically by entering all the parameters already used with the function Integral().

>>> integrate(f)
3 2
x + 2⋅ x + 5⋅ x >>>
integrate(f, (x, -2, 2))
36

As you can see, thanks to the integrate() function, it was possible to solve the integral both symbolically and numerically in a very immediate way. With a similar approach, it is also possible to solve double or triple integrals; we just have to specify the boundaries for each variable, in the same way we did for the x variable in the example above; in the next code lines, we calculate the double integral of the function “g”.

>>> g = x ** 2 + 5 * y >>>
integrate(g, (x, -2, 2), (y, 3, 5))
512 / 3