如何在Matplotlib中改变图例的位置

833 阅读2分钟

要改变Matplotlib中图例的位置,你可以使用plt.legend()函数。

例如,你可以使用下面的语法将图例放在绘图的左上角:

plt.legend(loc='upper left')

默认的位置是 "最佳"--这是Matplotlib根据避免覆盖任何数据点的位置自动为图例找到的位置。

然而,你可以指定以下任何一个图例位置:

  • 右上角
  • 左上角
  • 左下
  • 右下角
  • 右边
  • 中间偏左
  • 中间偏右
  • 下部中心
  • 上部中心
  • 中心

您也可以使用bbox_to_anchor()参数将图例置于绘图之外。例如,您可以使用下面的语法将图例放在绘图外的右上角。

plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)

下面的例子展示了如何在实践中使用这些方法。

例1:改变图例在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]})

#add lines to plot
plt.plot(df['points'], label='Points', color='green')
plt.plot(df['assists'], label='Assists', color='steelblue')

#place legend in center right of plot
plt.legend(loc='center right', title='Metric')

下面的代码显示了如何将图例放在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]})

#add lines to plot
plt.plot(df['points'], label='Points', color='green')
plt.plot(df['assists'], label='Assists', color='steelblue')

#place legend in center right of plot
plt.legend(loc='upper left', title='Metric')

例2:改变图例在Matplotlib绘图外的位置

要把图例放在Matplotlib图的外面,我们可以使用**bbox_to_anchor()**参数。

例如,这里是如何将图例放在绘图的右上角之外。

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

#add lines to plot
plt.plot(df['points'], label='Points', color='green')
plt.plot(df['assists'], label='Assists', color='steelblue')

#place legend in center right of plot
plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)

这里是如何将图例放在绘图的右下角之外的:

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

#add lines to plot
plt.plot(df['points'], label='Points', color='green')
plt.plot(df['assists'], label='Assists', color='steelblue')

#place legend in center right of plot
plt.legend(bbox_to_anchor=(1.02, 0.1), loc='upper left', borderaxespad=0)

关于bbox_to_anchor()参数的详细解释,请参考matplotlib文档

其他资源

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

如何在Matplotlib中改变图例字体大小
如何在Matplotlib中调整标题位置
如何在Matplotlib中调整轴标签位置