physicsnoob
physicsnoob

Reputation: 13

Plotting multiple 2d curves with matplotlib in 3d

I'm trying to plot a fourier series of a triangular wave with matplotlib.

I've managed to plot the elements on top of each other in 2d, but I'd like to plot them in 3d instead, as that makes it more easy to see.

Here's the plot my current code generates triangular wave

Here's an image of what I'd like to plot, but for the triangular wave instead of a square wave.

square wave

Here's the current code

%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()

Upvotes: 1

Views: 2852

Answers (1)

Mantxu
Mantxu

Reputation: 319

I have found a way based on this matplotlib official example. Add this code below your code and you will get something close to what you want:

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()

Upvotes: 1

Related Questions