使用matplotlib在3d

时间:2016-02-21 20:46:02

标签: python matplotlib

我试图用matplotlib绘制一个三角波的傅里叶级数。

我设法在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()

1 个答案:

答案 0 :(得分: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()