Home > Article > Backend Development > How to Add Labels to the Legend in Plots with Secondary Axes Using twinx()?
Adding Labels to the Legend in Plots with Secondary Axes Using twinx()
Having multiple axes in a single plot can be useful for visualizing data from different sources or with different units. When using the twinx() function to create a secondary axis, it may be necessary to add labels to the lines plotted on the secondary axis and include them in the legend.
To accomplish this, you can either add a separate legend for the secondary axis using ax2.legend(loc=0). However, this approach results in two separate legends.
For a more cohesive display, all labels can be added to a single legend using the following steps:
<code class="python">import numpy as np import matplotlib.pyplot as plt from matplotlib import rc time = np.arange(10) temp = np.random.random(10)*30 Swdown = np.random.random(10)*100-10 Rn = np.random.random(10)*100-10 fig = plt.figure() ax = fig.add_subplot(111) lns1 = ax.plot(time, Swdown, '-', label = 'Swdown') lns2 = ax.plot(time, Rn, '-', label = 'Rn') ax2 = ax.twinx() lns3 = ax2.plot(time, temp, '-r', label = 'temp') # Add all lines and labels to a single legend lns = lns1+lns2+lns3 labs = [l.get_label() for l in lns] ax.legend(lns, labs, 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()</code>
This code will produce a single legend that includes all the labels from the primary and secondary axes.
The above is the detailed content of How to Add Labels to the Legend in Plots with Secondary Axes Using twinx()?. For more information, please follow other related articles on the PHP Chinese website!