Home  >  Article  >  Backend Development  >  How to Add Labels to the Legend in Plots with Secondary Axes Using twinx()?

How to Add Labels to the Legend in Plots with Secondary Axes Using twinx()?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 04:32:30889browse

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:

  • Create a list of line objects representing all lines plotted on both axes.
  • Create a list of labels corresponding to the line objects.
  • Use the legend function to add the lines and labels to the legend, passing the loc parameter to specify the legend's location.
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn