如何改变Matplotlib图例中项目的顺序

2,897 阅读2分钟

你可以使用下面这块代码来改变Matplotlib图例中项目的顺序。

#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图例中项目的顺序

假设我们在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()

图例中的项目是按照我们将线条添加到图中的顺序放置的。

但是,我们可以使用下面的语法来定制图例中项目的顺序。

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

请注意,我们指定了。

  • order = [1, 2, 0]

这意味着

  • 图例中的第一个项目应该是原来在旧图例的索引位置1的标签("协助")。
  • 图例中的第二项应该是原来在旧图例的索引位置2的标签("篮板")。
  • 图例中的第三项应该是原来在旧图例索引位置标签("得分")。

其他资源

下面的教程解释了如何在Matplotlib中执行其他常见的操作。

如何在Matplotlib中改变图例的位置
如何将图例放在Matplotlib图的外面
如何在Matplotlib中改变图例字体大小

The postHow to Change Order of Items in Matplotlib Legendappeared first onStatology.