I am trying to plot two line graphs on top of each other, but at a scale where they both can be seen. Currently I am doing something like:
import matplotlib.pyplot as plt
data_1 = [1, 10, 30, 4, 50]
data_2 = [1000, 1020, 1050, 1300]
plt.plot(data_1)
plt.plot(data_2)
plt.show()
But this results in
What I want is the plots to be on top of each other, each with its own axis.
CodePudding user response:
One way to do this is to use separate Y axis for each line with ax.twinx
:
import matplotlib.pyplot as plt
data_1 = [1, 10, 30, 4, 50]
data_2 = [1000, 1020, 1050, 1300]
# Get Axes instances
fig, ax_left = plt.subplots()
ax_right = ax_left.twinx()
# Left Y axis
ax_left.plot(data_1, color='red', label='Data 1')
ax_left.set_ylabel('Data 1')
ax_left.legend()
# Right Y axis
ax_right.plot(data_2, color='orange', label='Data 2')
ax_right.set_ylabel('Data 2')
ax_right.legend()
plt.show()
output: