How to plot two different scales on one plot in matplotlib (with legend)
Here’s a breakdown of how this works:
# Plot two lines with different scales on the same plot
fig = plt.figure(figsize=(8, 5))
line_weight = 3alpha = .5
ax1 = fig.add_axes([0, 0, 1, 1])ax2 = fig.add_axes()
# This is the magic that joins the x-axisax2 = 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 legendsleg = lns1 + lns2labs = [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 legendsleg = lns1 + lns2labs = [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