2016-02-21 129 views
0

我想用matplotlib繪製一個三角波的fourier系列。用matplotlib在3d中繪製多條2d曲線

我已經設法在2D中繪製了彼此頂部的元素,但我想用3D來繪製它們,因爲這樣可以更容易看到它們。

這裏是我當前的代碼生成 triangular wave

這裏是想什麼,我繪製的圖像的情節,但對於三角波而不是方波。

square wave

下面是當前的代碼

%matplotlib inline 
import numpy as np 
from matplotlib import pyplot as plt 
import scipy as sp 

x1 = np.arange(0, L/2.0, 0.01) 
x2 = np.arange(L/2.0,L,0.01) 
x = np.concatenate((x1,x2)) 
y1 = 2* x1 
y2 = 2*(1 - x2) 
triangle_y = np.concatenate((y1,y2)) 
L = 1; 

def triangle_function(x, L): 
    '''given x, returns y as defined by the triangle function defined in the range 0 <= x <= L 
    ''' 
    if x< 0: 
     print 'Error: the value of x should be between 0 and L' 
     y = None 
    elif x<L/2.0: 
     y = 2*x 
    elif x <= L: 
     y = 2*(1 - x) 
    else: 
     print 'Error: the value of x should be between 0 and L' 
     y = None 
    return y 

def projection_integrand(x, n, L): 
    '''The inputs to the function are: 
    x ---> vector of x values. 
    n ---> the n-number associated to the sine functions 
    L --> L, upper limit of integration 
    ''' 
    sine_function = np.sin(n * np.pi * x/np.double(L)) # this is the sine function sin(n*pi*x/L) 
    integrand = (2.0/L) * sine_function * triangle_function(x, L) # this is the product of the two functions, with the 2/L factor 
    #return(sine_function*f_x) 
    return integrand 

from scipy.integrate import quad 

n_max = 5 
x = np.arange(0, L, 0.01) # x vector 
triangle_approx = np.zeros(len(x)) 
func_list = [] 

for n in range(1, n_max + 1): 
    c_n = quad(projection_integrand, 0, L, (n, L)) 
    sin_arg = n* np.pi*x/np.double(L) 
    current = c_n[0]* np.sin(sin_arg) 
    triangle_approx += current 
    func_list.append(current) 

from mpl_toolkits.mplot3d import Axes3D 

plt.hold(True) 
plt.plot(x, func_list[0]) 
plt.plot(x, func_list[1]) 
plt.plot(x, func_list[2]) 
plt.plot(x, func_list[3]) 
plt.plot(x, func_list[4]) 
plt.plot(x, triangle_approx) 
plt.plot(x, triangle_y) 
plt.xlabel('x') 
plt.ylabel('f(x)') 
plt.title('approximating the triangle function as a sum of sines, n = 1 ...' + str(n_max)) 
plt.legend(['approximation', 'triangle function']) 
plt.show() 

回答

0

我發現在此基礎上matplotlib official example的方式。 添加該代碼下面你的代碼,你會得到一些接近你想要什麼:

fig = plt.figure() 
ax = fig.gca(projection='3d') 
z = np.array([1.0 for point in x]) 
for n, armonic in enumerate(func_list): 
    ax.plot(x, armonic, z*n, label='armonic{}'.format(n)) 
ax.legend() 
plt.show() 
+0

我已經注意到,我忘了通過armonic在更換func_list [N] for循環。 – Mantxu

+0

如果需要,您可以編輯帖子。我已經爲你編輯了這一個 – tom