Home > Backend Development > Python Tutorial > How to Add Labels for Both Primary and Secondary Axes in a Legend with TwinX?

How to Add Labels for Both Primary and Secondary Axes in a Legend with TwinX?

Susan Sarandon
Release: 2024-11-01 01:09:01
Original
993 people have browsed it

How to Add Labels for Both Primary and Secondary Axes in a Legend with TwinX?

Legend Display with Secondary Axis in TwinX

In a plot with multiple y-axes using twinx(), adding labels to each line and displaying them in a legend can present a challenge. Typically, only labels from the primary axis appear in the legend.

Consider the following example where labels for two primary axis lines and one secondary axis line are defined:

<code class="python">fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
ax.legend(loc=0)</code>
Copy after login

In this case, the legend shows only the labels 'Swdown' and 'Rn'. To include the label 'temp' for the secondary axis, two approaches can be employed:

Separate Legends

One option is to create a second legend specifically for the secondary axis. This can be achieved by adding the following line:

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

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

Combined Legend

For a single, combined legend, use the following steps:

  1. Create a list of all the lines (from both axes) you want to appear in the legend:
<code class="python">lns = lns1+lns2+lns3</code>
Copy after login
  1. Extract the labels from each line:
<code class="python">labs = [l.get_label() for l in lns]</code>
Copy after login
  1. Use the legend() function on the primary axis (ax), passing in the combined line list and label list:
<code class="python">ax.legend(lns, labs, loc=0)</code>
Copy after login

By following these instructions, you can effectively display all line labels in a single legend, whether they belong to the primary or secondary axes.

The above is the detailed content of How to Add Labels for Both Primary and Secondary Axes in a Legend with TwinX?. 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