📅  最后修改于: 2023-12-03 14:53:24.665000             🧑  作者: Mango
当我们使用 Matplotlib 制作子图时,通常需要添加图例来解释每个子图的含义。本文将介绍如何在子图中添加 Matplotlib 图例。
以下是一个例子,展示如何在一个包含多个子图的 Matplotlib 图中添加图例:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# 创建子图
fig, axs = plt.subplots(2, 2)
# 子图 1
axs[0, 0].plot(x, x)
# 子图 2
axs[0, 1].plot(x, -x)
# 子图 3
axs[1, 0].plot(x, x**2)
# 子图 4
axs[1, 1].plot(x, np.sin(x))
# 将图例添加到第 4 个子图
axs[1, 1].legend(['sin(x)'])
# 显示图形
plt.show()
在该示例代码中,我们使用 plt.subplots()
函数创建了一个包含 2 行 2 列,共 4 个子图的 Matplotlib 图。然后我们给每个子图添加了不同的曲线,并对第四个子图添加了一个图例,其中包含了一个条目 "sin(x)"。
当我们添加图例时,可以通过传递位置参数调整图例的位置。以下是图例位置参数及其含义:
'best'
: Matplotlib 会尝试自动寻找最佳位置。'upper right'
: 右上角。'upper left'
: 左上角。'lower left'
: 左下角。'lower right'
: 右下角。'right'
: 右边界的中间。'center left'
: 左边界的中间。'center right'
: 右边界的中间。'lower center'
: 底部中心。'upper center'
: 顶部中心。'center'
: 图片的正中央。示例代码如下:
axs[1, 1].legend(['sin(x)'], loc='upper right')
在上述示例代码中,我们使用 loc
参数将图例位置设置为右上角。
Matplotlib 图例不仅可以调整位置,还可以设置样式。以下是图例样式参数及其含义:
'best'
: Matplotlib 会尝试自动寻找最佳位置。'upper right'
: 右上角。'upper left'
: 左上角。'lower left'
: 左下角。'lower right'
: 右下角。'right'
: 右边界的中间。'center left'
: 左边界的中间。'center right'
: 右边界的中间。'lower center'
: 底部中心。'upper center'
: 顶部中心。'center'
: 图片的正中央。示例代码如下:
axs[1, 1].legend(['sin(x)'], loc='upper right', frameon=False)
在上述示例代码中,我们使用 frameon
参数将图例的框架设置为无。True
表示有框架,False
表示无框架。
Matplotlib 中的图例是解释每个子图含义的重要组成部分。我们可以使用位置和样式参数来调整图例的位置和样式。本文提供了一个完整的示例,展示如何在子图中添加 Matplotlib 图例。