Reputation: 43
I have certain function, for example sin(b*x), with sympy I get derivative and antiderivative expressions, but I need to plot these 3 functions in matplotlib. My problem is I can't convert correctly functions to numpy in order to plot in matplotlib. I have followed the documentation in sympy page with lambify function but it doesn't work. http://docs.sympy.org/latest/modules/utilities/lambdify.html
I have this code:
from sympy import Symbol, diff, integrate, sin, cos, Function
from sympy.utilities.lambdify import lambdify, implemented_function
from sympy.abc import x
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
def signal(b,x):
return sin(b*x)
def derivative(b,x):
yprime = diff(signal(b,x), x)
return yprime
def antiderivative(b,x):
anti = integrate(signal(b,x), x)
return anti
b = 5
evalfunc = lambdify((b,x), signal(b,x), modules=['numpy'])
evalderiv = lambdify((b,x), derivative(b,x), modules=['numpy'])
evalantideriv = lambdify((b,x), antiderivative(b,x), modules=['numpy'])
axis_color = 'lightgoldenrodyellow'
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
fig.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(-10, 10, 0.001)
[line] = ax.plot(t, evalfunc(b,t), linewidth=2, color='red')
[line2] = ax.plot(t, evalderiv(b,t), linewidth=2, color='blue')
[line3] = ax.plot(t, evalantideriv(b,t), linewidth=2, color='blue')
ax.set_xlim([-10, 10])
ax.set_ylim([-5, 5])
ax.grid()
plt.show()
It fails in ax.plot ValueError: sequence too large; cannot be greater than 32
Upvotes: 1
Views: 2287
Reputation: 1565
Your code is not quite a minimal working example, but it requires only minimal changes to work.
You need to declare your b
as real symbol before the derivation.
You set it as b=5
before the numerical evaluation.
See:
from sympy import Symbol, diff, integrate, sin, cos, Function
from sympy.utilities.lambdify import lambdify, implemented_function
from sympy.abc import x
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
def signal(b,x):
return sin(b*x)
def derivative(b,x):
yprime = diff(signal(b,x), x)
return yprime
def antiderivative(b,x):
anti = integrate(signal(b,x), x)
return anti
b = Symbol('b', real=True)
evalfunc = lambdify((b,x), signal(b,x), modules=['numpy'])
evalderiv = lambdify((b,x), derivative(b,x), modules=['numpy'])
evalantideriv = lambdify((b,x), antiderivative(b,x), modules=['numpy'])
axis_color = 'lightgoldenrodyellow'
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
fig.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(-10, 10, 0.001)
b = 5
[line] = ax.plot(t, evalfunc(b,t), linewidth=2, color='red')
[line2] = ax.plot(t, evalderiv(b,t), linewidth=2, color='blue')
[line3] = ax.plot(t, evalantideriv(b,t), linewidth=2, color='blue')
ax.set_xlim([-10, 10])
ax.set_ylim([-5, 5])
ax.grid()
plt.show()
Upvotes: 2