Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to reverse order of legend in Matplotlib

📅 2019-Sep-12 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ matplotlib ⬩ 📚 Archive

The labels displayed in the Matplotlib legend are displayed in the same order in which they are plotted. This can be a problem for plots such as a stack plot. While the data is stacked from bottom to top, the legend displays those labels from top to bottom. This can make the plot confusing.

To reverse the order of the labels, we first grab its handles and set the handles and labels in reversed order:

import matplotlib.pyplot as pyplot

# Draw a stackplot
pyplot.stackplot(x, y_vals, labels=labels)

# Reverse the order of labels in legend
pyplot.legend(reversed(pyplot.legend().legendHandles), reversed(labels))

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧