52
You can use the following chunk of code to change the order of items in a Matplotlib legend:
#get handles and labels handles, labels = plt.gca().get_legend_handles_labels() #specify order of items in legend order = [1,2,0] #add legend to plot plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
The following example shows how to use this syntax in practice.
Example: Change Order of Items in Matplotlib Legend
Suppose we create the following line chart in Matplotlib:
import pandas as pd import matplotlib.pyplot as plt #create data df = pd.DataFrame({'points': [11, 17, 16, 18, 22, 25, 26, 24, 29], 'assists': [5, 7, 7, 9, 12, 9, 9, 4, 8], 'rebounds': [6, 8, 8, 10, 14, 12, 12, 10, 11]}) #add lines to plot plt.plot(df['points'], label='Points', color='green') plt.plot(df['assists'], label='Assists', color='steelblue') plt.plot(df['rebounds'], label='Rebounds', color='purple') #add legend plt.legend()
The items in the legend are placed in the order that we added the lines to the plot.
However, we can use the following syntax to customize the order of the items in the legend:
import pandas as pd import matplotlib.pyplot as plt #create data df = pd.DataFrame({'points': [11, 17, 16, 18, 22, 25, 26, 24, 29], 'assists': [5, 7, 7, 9, 12, 9, 9, 4, 8], 'rebounds': [6, 8, 8, 10, 14, 12, 12, 10, 11]}) #add lines to plot plt.plot(df['points'], label='Points', color='green') plt.plot(df['assists'], label='Assists', color='steelblue') plt.plot(df['rebounds'], label='Rebounds', color='purple') #get handles and labels handles, labels = plt.gca().get_legend_handles_labels() #specify order of items in legend order = [1,2,0] #add legend to plot plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
Note that we specified:
- order = [1, 2, 0]
This means:
- The first item in the legend should be the label that was originally in index position 1 of the old legend (“Assists”)
- The second item in the legend should be the label that was originally in index position 2 of the old legend (“Rebounds”)
- The third item in the legend should be the label that was originally in index position 0 of the old legend (“Points”)
Additional Resources
The following tutorials explain how to perform other common operations in Matplotlib:
How to Change the Position of a Legend in Matplotlib
How to Place the Legend Outside of a Matplotlib Plot
How to Change Legend Font Size in Matplotlib