Home > Backend Development > Python Tutorial > 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
Release: 2024-11-01 06:16:01
Original
582 people have browsed it

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)
Copy after login

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(...)
    Copy after login
  2. Define the legend handles and labels:

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

    ax.legend(lns, labs, loc=0)
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template