Your code is repeating a little bit. For example,
ax[0].plot(x, sine)
ax[0].set_title('Sine wave')
ax[1].plot(x, cosine)
ax[1].set_title('Cosine wave')
ax[2].plot(x, superposition)
ax[2].set_title('Bichromatic wave')
This can be rewritten using a helper function (or alternatively a for-loop), which may look something like this:
def plot_subroutine(axis, xdata, ydata, title):
axis.plot(xdata, ydata)
axis.set_title(title)
y1 = ... # sine
y2 = ... # cosine
y3 = ... # bichromatic
yn = (y1, y2, y3)
title1 = 'Sine Wave'
title2 = 'Cosine Wave'
title3 = 'Bichromatic Wave'
titles = (title1, title2, title3)
fig, ax = plt.subplots(3,1)
# or use a for-loop
Then instead of calling each plot subroutine individually (as below)
plot_subroutine(ax[0], x, yn[0])
plot_subroutine(ax[1], x, yn[1])
plot_subroutine(ax[2], x, yn[2])
You can instead do something like
if len(ax) == len(yn):
for i in range(len(ax)):
plot_subroutine(ax[i], x, yn[i])
plt.show()
The for-loop has the advantage that you can later change the number of output plots without changing too much of your original code (if say, you wanted to output 2 or 4 plots, or perhaps change the ydata
to something entirely different).
This may or may not be relevant, but it may be nice to associate each individual plot with a specific legend label, marker style, and/or color, all of which can be handled using matplotlib
. This can be especially useful for overlayed plots (especially considering that your data consists of sin(x)
and cos(x)
over the same x-interval.