如何在 Matplotlib 中更改 "legend" 的位置

2025年3月17日 | 阅读 3 分钟

在本教程中,我们将讨论如何在 Matplotlib 中更改图例的位置。

首先,我们将讨论一些基本概念

  • Matplotlib 是一个用 Python 编写的强大可视化库,用于绘制 2D 数组图。它由 John Hunter 于 2002 年开发。Matplotlib 是一个基于 NumPy 数组的多平台数据可视化工具,旨在与更广泛的 SciPy 堆栈集成。
  • 图例是描述图中各种元素的区域。在 matplotlib 库中,有一个名为 legend() 的函数可用于创建特定于轴的图例。
  • legend() 中的此属性 Loc 用于定义图例的确切位置。Loc 的默认值为 loc = "best"(左上角)。字符串 best、upper left、upper right、lower left、lower right、middle left、middle right、lower center、upper center 和 center 将把图例放置在轴/图形的相应区域。
位置字符串位置字符串
最佳0
右上角1
左上角2
左下角3
右下角4
5
左中6
右中7
下中8
上中9
中心10

方法

  • 步骤 1:我们将导入所需的模块和库。
  • 步骤 2:我们将导入或创建数据。
  • 步骤 3:我们将绘制图表
  • 步骤 4:我们将添加图例
  • 步骤 5:我们将使用 loc 设置图例的位置。

示例 1

输出

How to Change the legend Position in Matplotlib

示例 2:在右上角设置位置

输出

How to Change the legend Position in Matplotlib

示例 3:图例位于左下角,也为“3”

输出

How to Change the legend Position in Matplotlib

左下角图例

示例 4:图例位于中心位置

输出

How to Change the legend Position in Matplotlib

结论

在本教程中,我们演示了如何在 Python 中使用 Matplotlib 更改图例的位置。