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:
lns = lns1 lns2 lns3
labs = [l.get_label() for l in lns]
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.
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