'Create subplots on the same page

How do I subplots multiple graphs? so it will look like the picture. the image is how the plots should look Im able to plot individule but i cant figure out

A = 1  # Wave amplitude in meters
T = 10  # Time Period in secs
pi = 3.14  # Value of pi
n_w = 10 # Number of waves
wavelength = 156  # Wavelength in meters


k = (2 * pi) / wavelength
w = (2 * pi) / T

def wave_elevation(x,t):
    return A * np.cos((k * x) - (w * t))

t_list = np.array([0,0.25,0.5,0.75,1.0])*T

for t in t_list:
    wave_ele_Val = []
    for i in np.linspace(0,wavelength*n_w,1560):
        wave_ele_Val.append(wave_elevation(i,t))
    fig, ax = plt.subplots(figsize=(15, 5))
    plt.plot(np.linspace(0,wavelength*n_w,1560),wave_ele_Val,'r')
    plt.title("Wave Elevation-Space Variations @ " + str(t) + "* Time Periods")
    plt.xlabel("x (m)")
    plt.ylabel("\u03B7")
    plt.grid()
    plt.show()


Solution 1:[1]

You need to specify how many subplots you want:

matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

In your case this would be plt.subplots(5)

The plt.plot() needs to be changed to ax[i].plot(x,y) Where i is your number of subplot.

Also shift the plt.show() outside of the loop, so it is called at the end and not in between.

This is one example, how you can do it:

x_list = np.array([0,0.25,0.5,0.75,1.0])*wavelength
fig, ax = plt.subplots(5, figsize=(15, 5))

for j,x in enumerate(x_list):
    wave_ele_Val = []
    for i in np.linspace(0,T*n_w,1000):
        wave_ele_Val.append(wave_elevation(x, i))
    ax[j].plot(np.linspace(0,T*n_w,1000),wave_ele_Val)
    ax[j].grid()
    ax[j].set_title("Wave Elevation-Time Variations @ " + str(x) + "WaveLengths")
    ax[j].set_ylabel("\u03B7")

fig.tight_layout()
plt.xlabel("Time (s)")
plt.show()

This gives me:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1