When using twinx() to create multiple y-axes on a plot, it's desirable to display all associated labels in the legend.
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).
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.
Alternatively, to combine all labels into a single legend, follow these steps:
<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!