y-y plots are a type of line plot where one line corresponds to one y-axis, and another line on the same plot corresponds to a different y-axis. y-y plots typically have one vertical y-axis on the left edge of the plot and one vertical y-axis on the right edge of the plot.

# How to make y-y plots with Matplotlib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import sys
#mpl.style.use("seaborn")
mpl.style.use("default")
print(f'Python version {sys.version}')
print(f'Matplotlib version {mpl.__version__}')
print(f'NumPy version {np.__version__}')
x = np.arange(0,4*np.pi,0.1)
y1 = np.cos(x)
y2 = np.exp(x)

# plot function y1
fig, ax = plt.subplots()
ax.plot(x,y1)
ax.set_title('sin(x)')
plt.show()

# plot function y2
fig, ax = plt.subplots()
ax.plot(x,y2)
ax.set_title('exp(x)')
plt.show()

# plot two functions
fig, ax = plt.subplots()
ax.plot(x,y1)
ax.plot(x,y2)
ax.set_title('sin(x) and exp(x)')
ax.legend(['sin(x)','exp(x)'])
plt.show()

# two subplots
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12,4))
ax1.plot(x,y1)
ax1.set_title('sin(x)')
ax2.plot(x,y2,'C3')
ax2.set_title('exp(x)')
plt.show()

# y-y plot using twinx
fig, ax1 = plt.subplots()
ax1.plot(x,y1)
ax1.set_title('sin(x) and exp(x)')
ax2 = ax1.twinx()
ax2.plot(x,y2,'C3')
plt.show()

# color each y axis
fig, ax1 = plt.subplots()
ax1.plot(x,y1)
ax1.set_ylabel('sin(x)', color='C0')
ax1.tick_params(axis='y', color='C0', labelcolor='C0')
ax1.set_title('sin(x) and exp(x)')
ax2 = ax1.twinx()
ax2.plot(x,y2,'C3')
ax2.set_ylabel('exp(x)', color='C3')
ax2.tick_params(axis='y', color='C3', labelcolor='C3')
ax2.spines['right'].set_color('C3')
ax2.spines['left'].set_color('C0')
plt.show()


# add a legends
fig, ax1 = plt.subplots()
ax1.plot(x,y1)
ax1.set_ylabel('sin(x)', color='C0')
ax1.tick_params(axis='y', color='C0', labelcolor='C0')
ax1.set_title('sin(x) and exp(x)')
ax2 = ax1.twinx()
ax2.plot(x,y2,'C3')
ax2.set_ylabel('exp(x)', color='C3')
ax2.tick_params(axis='y', color='C3', labelcolor='C3')
ax2.spines['right'].set_color('C3')
ax2.spines['left'].set_color('C0')
fig.legend(['sin(x)','exp(x)'], bbox_to_anchor=(0.9, 0.8))
plt.show()


# alternative way to add legends
fig, ax1 = plt.subplots()
line1 = ax1.plot(x,y1)
ax1.set_ylabel('sin(x)', color='C0')
ax1.tick_params(axis='y', color='C0', labelcolor='C0')
ax1.set_title('sin(x) and exp(x)')
ax2 = ax1.twinx()
line2 = ax2.plot(x,y2,'C3')
ax2.set_ylabel('exp(x)', color='C3')
ax2.tick_params(axis='y', color='C3', labelcolor='C3')
ax2.spines['right'].set_color('C3')
ax2.spines['left'].set_color('C0')
lines = line1 + line2
ax2.legend(lines, ['sin(x)','exp(x)'])
plt.savefig('ex296.png', dpi=72)
plt.show()

Discover more from Tips and Hints for Aerospace Engineers

Subscribe now to keep reading and get access to the full archive.

Continue reading