Secondary axis with twinx(): how to add to legend?

I have a plot with two y-axes, using twinx(). I also give labels to the lines, and want to show them with legend(), but I only succeed to get the labels of one axis in the legend:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default="regular")

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label="Swdown")
ax.plot(time, Rn, '-', label="Rn")
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label="temp")
ax.legend(loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

So I only get the labels of the first axis in the legend, and not the label ‘temp’ of the second axis. How could I add this third label to the legend?

enter image description here

9 Answers
9

Leave a Comment