There are quite a few resources on the web for constructing a chart in Matplotlib with multiple y-axes.
See:
https://matplotlib.org/gallery/ticks_and_spines/multiple_yaxis_with_spines.html
matplotlib: overlay plots with different scales?
Constructing a chart with up to three y-axes is not difficult. However, a chart with four or five y_axes becomes more difficult to get the spacing of the placement of the y_axes nice looking.
Is there a repeatable approach to get the spacing of the extra Y-axes to be non-overlapping?
In particular, in the code below the calls to
fig.subplots_adjust(right=...)
and
ax.spines["right"].set_position(("axes",...))
ought to be refined to account for the width of the preceding y-axis displays (in particular, the width of the numbers displayed in the y-axis display).
I'm using Python 3.6.4, Matplotlib 2.1.2, and Qt5Agg as the Matplotlib backend on Windows 10.
import matplotlib.pyplot as plt
plt.ioff()
def adjust_extra_yaxes(ax, pct_shift):
ax.spines["right"].set_position(("axes", 1+pct_shift))
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.values():
sp.set_visible(False)
ax.spines["right"].set_visible(True)
fig, ax_0 = plt.subplots()
ax_1 = ax_0.twinx()
ax_2 = ax_0.twinx()
ax_3 = ax_0.twinx()
ax_4 = ax_0.twinx()
num_extra_yaxes = 3
pct_width_per_yaxis = 0.1
fig_right_margin = 1.0 - pct_width_per_yaxis*num_extra_yaxes
fig.subplots_adjust(right=fig_right_margin)
i = 1
for ax in [ax_2, ax_3, ax_4]:
adjust_extra_yaxes(ax, pct_width_per_yaxis*i)
i+=1
l0, = ax_0.plot([0, 1, 2], [0, 1, 2], linestyle='-', label="Label Name 0", color='Blue')
l1, = ax_1.plot([0, 1, 2], [0, 3000000, 2000000], linestyle='-', label="Label Name 1", color='Green')
l2, = ax_2.plot([0, 1, 2], [5, 3, 1.5], linestyle='-', label="Label Name 2", color='Red')
l3, = ax_3.plot([0, 1, 2], [800000, 200000, 150000], linestyle='-', label="Label Name 3", color='cyan')
l4, = ax_4.plot([0, 1, 2], [50, 55, 200], linestyle='-', label="Label Name 4", color='black')
ax_0.set_xlim(0, 2)
ax_0.set_ylim(0, 2)
ax_1.set_ylim(0, 3000000)
ax_2.set_ylim(1, 5)
ax_3.set_ylim(100000, 800000)
ax_4.set_ylim(0, 200)
ax_0.set_xlabel("X-Axis Label")
ax_0.set_ylabel("Label Name 0")
ax_1.set_ylabel("Label Name 1")
ax_2.set_ylabel("Label Name 2")
ax_3.set_ylabel("Label Name 3")
ax_4.set_ylabel("Label Name 4")
ax_0.yaxis.label.set_color(l0.get_color())
ax_1.yaxis.label.set_color(l1.get_color())
ax_2.yaxis.label.set_color(l2.get_color())
ax_3.yaxis.label.set_color(l3.get_color())
ax_4.yaxis.label.set_color(l4.get_color())
tkw = dict(size=4, width=1.5)
ax_0.tick_params(axis='y', colors=l0.get_color(), **tkw)
ax_1.tick_params(axis='y', colors=l1.get_color(), **tkw)
ax_2.tick_params(axis='y', colors=l2.get_color(), **tkw)
ax_3.tick_params(axis='y', colors=l3.get_color(), **tkw)
ax_4.tick_params(axis='y', colors=l4.get_color(), **tkw)
ax_0.tick_params(axis='x', **tkw)
lines = [l0, l1, l2, l3, l4]
ax_0.legend(lines, [l.get_label() for l in lines])
plt.show()