Home > Article > Backend Development > 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>
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>
This will result in two separate legends, one for each axis.
Combined Legend
For a single, combined legend, use the following steps:
<code class="python">lns = lns1+lns2+lns3</code>
<code class="python">labs = [l.get_label() for l in lns]</code>
<code class="python">ax.legend(lns, labs, loc=0)</code>
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!