Home > Article > Backend Development > How do I display labels from both axes in a single legend when using `twinx()` in Matplotlib?
Adding a Secondary Axis Legend to a Twinx() Plot
In a plot with two y-axes created using twinx(), adding labels to the lines and displaying them in a legend can be challenging. Initially, only the labels from the primary axis may appear in the legend.
To resolve this issue, add a legend for the secondary axis using the line:
ax2.legend(loc=0)
This will result in two separate legends, one for each axis.
However, if you want all labels on a single legend, follow these steps:
Define both axes and plot the lines:
ax = fig.add_subplot(111) ax2 = ax.twinx() lns1 = ax.plot(...) lns2 = ax.plot(...) lns3 = ax2.plot(...)
Define the legend handles and labels:
lns = lns1 + lns2 + lns3 labs = [l.get_label() for l in lns]
Add the legend using:
ax.legend(lns, labs, loc=0)
This approach will display all axis labels in a single legend.
The above is the detailed content of How do I display labels from both axes in a single legend when using `twinx()` in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!