Home  >  Article  >  Backend Development  >  How do I display labels from both axes in a single legend when using `twinx()` in Matplotlib?

How do I display labels from both axes in a single legend when using `twinx()` in Matplotlib?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 06:16:01470browse

How do I display labels from both axes in a single legend when using `twinx()` in Matplotlib?

Adding a Secondary Axis Legend to a Twinx() Plot

In a plot with two y-axes created using twinx(), adding labels to the lines and displaying them in a legend can be challenging. Initially, only the labels from the primary axis may appear in the legend.

To resolve this issue, add a legend for the secondary axis using the line:

ax2.legend(loc=0)

This will result in two separate legends, one for each axis.

However, if you want all labels on a single legend, follow these steps:

  1. Define both axes and plot the lines:

    ax = fig.add_subplot(111)
    ax2 = ax.twinx()
    
    lns1 = ax.plot(...)
    lns2 = ax.plot(...)
    lns3 = ax2.plot(...)
  2. Define the legend handles and labels:

    lns = lns1 + lns2 + lns3
    labs = [l.get_label() for l in lns]
  3. Add the legend using:

    ax.legend(lns, labs, loc=0)

This approach will display all axis labels in a single legend.

The above is the detailed content of How do I display labels from both axes in a single legend when using `twinx()` in Matplotlib?. 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