Bimo
Bimo

Reputation: 6587

plotting sympy function using numpy and matplotlib

Here's what i'm trying to do:

# the standard broiler plate for jupyter
%matplotlib inline
from matplotlib.pyplot import *
from sympy import *
import numpy as np
init_printing()

t = symbols('t')

x1 = 2*cos(3*pi*t + pi/4)
x2 = x1.diff(t)
display(x1)
display(x2)

pi2 = 2*np.pi
vt  = np.arange(0, pi2, 0.1)
vx1 = np.zeros(len(tv))
vx2 = np.zeros(len(tv))

for n in range(0,len(vt)):
    vx1[n] = N(x1.subs(t,vt[n]))
    vx2[n] = N(x2.subs(t,vt[n]))

title('Signal')
plot(vt, vx1)
show()

title('Derivative of signal')
plot(vt, vx2)
show()

The above seems like it should work... however, I'm getting unexpected error message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-41-eaccf9c2bc6b> in <module>()
     14 
     15 title('Signal')
---> 16 plot(vt, vx1)
     17 show()
     18 title('Instantanious Frequency')

C:\Python35\lib\site-packages\sympy\plotting\plot.py in plot(*args, **kwargs)
   1289     series = []
   1290     plot_expr = check_arguments(args, 1, 1)
-> 1291     series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr]
   1292 
   1293     plots = Plot(*series, **kwargs)

TypeError: 'NoneType' object is not iterable

Upvotes: 0

Views: 2048

Answers (1)

caverac
caverac

Reputation: 1637

matplotlib.pyplot has a plot method, and so does sympy, when you do import * it is going to get a bit confusing

%matplotlib inline
import matplotlib.pyplot as plt
import sympy
import numpy as np
sympy.init_printing()

t = sympy.symbols('t')

x1 = 2 * sympy.cos(3 * sympy.pi * t + sympy.pi / 4)
x2 = x1.diff(t)
display(x1)
display(x2)

pi2 = 2 * np.pi
vt  = np.arange(0, pi2, 0.1)
vx1 = np.zeros(len(vt))
vx2 = np.zeros(len(vt))

for n in range(0,len(vt)):
    vx1[n] = sympy.N(x1.subs(t, vt[n]))
    vx2[n] = sympy.N(x2.subs(t,vt[n]))

plt.title('Signal')
plt.plot(vt, vx1)
plt.show()

plt.title('Derivative of signal')
plt.plot(vt, vx2)
plt.show()

enter image description here

Upvotes: 1

Related Questions