简介
在本实验中,你将学习如何使用 Matplotlib(一个用于创建可视化的 Python 库)来创建一个图形并注释其各个部分。你将学习如何创建图形、绘制数据、设置轴限制、添加标签和标题,以及用文本和标记注释图形。
虚拟机提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
导入库并设置数据
首先,我们需要导入必要的库并设置一些要绘制的数据。在这个例子中,我们将绘制三个添加了一些随机噪声的正弦波。
import matplotlib.pyplot as plt
import numpy as np
## 设置数据
np.random.seed(19680801)
X = np.linspace(0.5, 3.5, 100)
Y1 = 3+np.cos(X)
Y2 = 1+np.cos(1+X/0.75)/2
Y3 = np.random.uniform(Y1, Y2, len(X))
创建图形并设置坐标轴
接下来,我们将创建一个图形并设置坐标轴。我们将使用add_axes()方法在图形中创建一组新的坐标轴。我们还将设置 x 轴和 y 轴的范围,并添加网格线。
## 创建图形和坐标轴
fig = plt.figure(figsize=(7.5, 7.5))
ax = fig.add_axes([0.2, 0.17, 0.68, 0.7], aspect=1)
## 设置范围和网格线
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)
绘制数据
现在我们将在刚刚创建的坐标轴上绘制数据。我们将使用plot()方法以不同的颜色和线宽绘制三个正弦波。
## 绘制数据
ax.plot(X, Y1, c='C0', lw=2.5, label="Blue signal", zorder=10)
ax.plot(X, Y2, c='C1', lw=2.5, label="Orange signal")
ax.plot(X[::3], Y3[::3], linewidth=0, markersize=9,
marker='s', markerfacecolor='none', markeredgecolor='C4',
markeredgewidth=2.5)
添加标签和标题
现在我们将使用set_xlabel()、set_ylabel()和set_title()方法为 x 轴和 y 轴添加标签,并为图形添加标题。
## 添加标签和标题
ax.set_xlabel("x Axis label", fontsize=14)
ax.set_ylabel("y Axis label", fontsize=14)
ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment='bottom')
添加图例
我们将使用legend()方法为图形添加一个图例。我们还将指定图例的位置和字体大小。
## 添加图例
ax.legend(loc="upper right", fontsize=14)
为图形添加注释
最后,我们将使用text()和Circle()方法为图形添加注释,以展示各种 Matplotlib 元素的名称。我们还将使用withStroke()方法为文本和标记添加白色轮廓,以提高可见性。
## 为图形添加注释
from matplotlib.patches import Circle
from matplotlib.patheffects import withStroke
royal_blue = [0, 20/256, 82/256]
def annotate(x, y, text, code):
## 圆形标记
c = Circle((x, y), radius=0.15, clip_on=False, zorder=10, linewidth=2.5,
edgecolor=royal_blue + [0.6], facecolor='none',
path_effects=[withStroke(linewidth=7, foreground='white')])
ax.add_artist(c)
## 将 path_effects 用作文本的背景
## 分别绘制 path_effects 和彩色文本,以便 path_effects 不会裁剪其他文本
for path_effects in [[withStroke(linewidth=7, foreground='white')], []]:
color = 'white' if path_effects else royal_blue
ax.text(x, y-0.2, text, zorder=100,
ha='center', va='top', weight='bold', color=color,
style='italic', fontfamily='Courier New',
path_effects=path_effects)
color = 'white' if path_effects else 'black'
ax.text(x, y-0.33, code, zorder=100,
ha='center', va='top', weight='normal', color=color,
fontfamily='monospace', fontsize='medium',
path_effects=path_effects)
annotate(3.5, -0.13, "次要刻度标签", "ax.xaxis.set_minor_formatter")
annotate(-0.03, 1.0, "主要刻度", "ax.yaxis.set_major_locator")
annotate(0.00, 3.75, "次要刻度", "ax.yaxis.set_minor_locator")
annotate(-0.15, 3.00, "主要刻度标签", "ax.yaxis.set_major_formatter")
annotate(1.68, -0.39, "x 轴标签", "ax.set_xlabel")
annotate(-0.38, 1.67, "y 轴标签", "ax.set_ylabel")
annotate(1.52, 4.15, "标题", "ax.set_title")
annotate(1.75, 2.80, "线条", "ax.plot")
annotate(2.25, 1.54, "标记", "ax.scatter")
annotate(3.00, 3.00, "网格", "ax.grid")
annotate(3.60, 3.58, "图例", "ax.legend")
annotate(2.5, 0.55, "坐标轴", "fig.subplots")
annotate(4, 4.5, "图形", "plt.figure")
annotate(0.65, 0.01, "x 轴", "ax.xaxis")
annotate(0, 0.36, "y 轴", "ax.yaxis")
annotate(4.0, 0.7, "脊柱", "ax.spines")
总结
在本实验中,你学习了如何使用 Matplotlib 创建图形并注释其各个部分。你学习了如何创建图形、绘制数据、设置坐标轴范围、添加标签和标题,以及用文本和标记为图形添加注释。通过遵循本实验中的步骤,你现在应该对如何使用 Matplotlib 在 Python 中创建和注释图形有了很好的理解。