Home >Backend Development >Python Tutorial >How to Display All Labels in a Legend with twinx()?

How to Display All Labels in a Legend with twinx()?

DDD
DDDOriginal
2024-11-02 21:25:031093browse

How to Display All Labels in a Legend with twinx()?

Secondary Axis with twinx(): Enhancing Legend Display

When using twinx() to create multiple y-axes on a plot, it's desirable to display all associated labels in the legend.

Initial Issue

Consider this code snippet:

<code class="python">ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
ax.legend(loc=0)</code>

In this scenario, the legend only displays labels from the primary axis (ax), omitting the label for the secondary axis (ax2).

Adding a Separate Legend

To add a second legend for the secondary axis, simply include the following line:

<code class="python">ax2.legend(loc=0)</code>

This will create a separate legend for the labels associated with the secondary axis.

Combining Legends

Alternatively, to combine all labels into a single legend, follow these steps:

  1. Create a list of all line objects (lns).
  2. Generate a list of corresponding labels (labs).
  3. Call ax.legend() using both lists to create a single legend:
<code class="python">lns = lns1 + lns2 + lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)</code>

The above is the detailed content of How to Display All Labels in a Legend with 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