9951 explained code solutions for 126 technologies

python-matplotlibHow to change legend labels order

import matplotlib.pyplot as plt
plt.plot([1,2,10,6,15,3,4], label='A')
plt.plot([4,2,11,2,1,20,25], label='B')

h, l = plt.gca().get_legend_handles_labels()
plt.legend([h[1], h[0]], [l[1], l[0]])

plt.show()ctrl + c
import matplotlib.pyplot as plt

loads Matplotlib module to use plotting capabilities


plot specified data


set label for this line


returns legend labels and handlers


show and configure legend (we use default configuration in our case)

[h[1], h[0]], [l[1], l[0]]

we pass legend handles and labels in reverse order to reverse order


render chart in a separate window