How to plot two different scales on one plot in matplotlib (with legend)

samcha
Oct 17, 2018
# Plot two lines with different scales on the same plotfig = plt.figure(figsize=(8, 5))line_weight = 3
alpha = .5
ax1 = fig.add_axes([0, 0, 1, 1])
ax2 = fig.add_axes()
# This is the magic that joins the x-axis
ax2 = ax1.twinx()
lns1 = ax1.plot(wnv3['mosq'], color='blue', lw=line_weight, alpha=alpha, label='Mosquitos')
lns2 = ax2.plot(wnv3['wnv'], color='orange', lw=line_weight, alpha=alpha, label='Westnile')
# Solution for having two legends
leg = lns1 + lns2
labs = [l.get_label() for l in leg]
ax1.legend(leg, labs, loc=0)
plt.title('Cumulative yearly mosquito & West Nile levels', fontsize=20)

plt.show()

Here’s a breakdown of how this works:

ax2 = ax1.twinx()

The magic of the graph is the .twinx() element, which makes the new axis share the old axes x-axis, but keeps an independent y-axis.

# Solution for having two legends
leg = lns1 + lns2
labs = [l.get_label() for l in leg]
ax1.legend(leg, labs, loc=0)

One difficulty with this is creating a legend with both labels. There is no default way to do this, and calling two .legends() will result in one legend being on top of the other.

One solution is to set different loc variables in .legend(), but this looks too annoying.

Thanks to this StackOverflow thread, we have the above solution to getting everything onto one legend.

Anything I can write about to help you find success in data science or trading? Tell me about it here: https://bit.ly/3mStNJG

--

--

samcha

Python, trading, data viz. Get access to samchaaa++ for ready-to-implement algorithms and quantitative studies: https://samchaaa.substack.com/