"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-08
Browse:878

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:

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)

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:

ax2.legend(loc=0)

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:
lns = lns1 lns2 lns3
  1. Extract the labels from each line:
labs = [l.get_label() for l in lns]
  1. Use the legend() function on the primary axis (ax), passing in the combined line list and label list:
ax.legend(lns, labs, loc=0)

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3