matplotlib twinx legend

Solutions on MaxInterview for matplotlib twinx legend by the best coders in the world

showing results for - "matplotlib twinx legend"
Josefa
15 Sep 2020
1import numpy as np
2import matplotlib.pyplot as plt
3from matplotlib import rc
4rc('mathtext', default='regular')
5
6time = np.arange(10)
7temp = np.random.random(10)*30
8Swdown = np.random.random(10)*100-10
9Rn = np.random.random(10)*100-10
10
11fig = plt.figure()
12ax = fig.add_subplot(111)
13
14lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
15lns2 = ax.plot(time, Rn, '-', label = 'Rn')
16ax2 = ax.twinx()
17lns3 = ax2.plot(time, temp, '-r', label = 'temp')
18
19# added these three lines
20lns = lns1+lns2+lns3
21labs = [l.get_label() for l in lns]
22ax.legend(lns, labs, loc=0)
23
24ax.grid()
25ax.set_xlabel("Time (h)")
26ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
27ax2.set_ylabel(r"Temperature ($^\circ$C)")
28ax2.set_ylim(0, 35)
29ax.set_ylim(-20,100)
30plt.show()
31