How to Change Order of Items in Matplotlib Legend?

To change the order of items in a Matplotlib legend, use the plt.legend() function and specify the order in which the items appear in the keyword argument “labels”. This is a list of the labels in the order that you want them to appear in the legend. You can also use the “loc” keyword argument to specify the location of the legend. If you want to further customize the legend, you can use the legend() function’s additional keyword arguments.


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]) 

Matplotlib legend 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”)

The following tutorials explain how to perform other common operations in Matplotlib:

x