Matplotlib 路径效果教程

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,你将学习如何在 Matplotlib 中使用路径效果为你的绘图添加特效。路径效果允许你为文本和绘图元素添加自定义笔触、阴影和其他视觉效果。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。

导入库并准备数据

首先,我们需要导入必要的库并准备一些用于绘图的数据。

import matplotlib.pyplot as plt
import numpy as np

## 准备数据
arr = np.arange(25).reshape((5, 5))

为文本添加描边效果

我们可以使用 withStroke 路径效果为文本添加描边效果。在这个例子中,我们将为绘图中的文本注释添加描边效果。

## 创建绘图并添加带有描边效果的文本注释
fig, ax = plt.subplots()
ax.imshow(arr)
txt = ax.annotate("test", (1., 1.), (0., 0),
                   arrowprops=dict(arrowstyle="->",
                                   connectionstyle="angle3", lw=2),
                   size=20, ha="center",
                   path_effects=[patheffects.withStroke(linewidth=3,
                                                        foreground="w")])
txt.arrow_patch.set_path_effects([
    patheffects.Stroke(linewidth=5, foreground="w"),
    patheffects.Normal()])

## 添加带有描边效果的网格
pe = [patheffects.withStroke(linewidth=3,
                             foreground="w")]
ax.grid(True, linestyle="-", path_effects=pe)

plt.show()

为等高线添加描边效果

我们还可以使用 withStroke 路径效果为等高线及其标签添加描边效果。

## 创建绘图并添加带有描边效果的等高线
fig, ax = plt.subplots()
ax.imshow(arr)
cntr = ax.contour(arr, colors="k")

plt.setp(cntr.collections, path_effects=[
    patheffects.withStroke(linewidth=3, foreground="w")])

clbls = ax.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
plt.setp(clbls, path_effects=[
    patheffects.withStroke(linewidth=3, foreground="w")])

plt.show()

为图例添加阴影效果

我们可以使用 withSimplePatchShadow 路径效果为图例添加阴影效果。

## 创建绘图并为图例添加阴影效果
fig, ax = plt.subplots()
p1, = ax.plot([0, 1], [0, 1])
leg = ax.legend([p1], ["Line 1"], fancybox=True, loc='upper left')
leg.legendPatch.set_path_effects([patheffects.withSimplePatchShadow()])

plt.show()

总结

在这个实验中,你学习了如何在 Matplotlib 中使用路径效果为你的绘图添加特殊效果。你学习了如何为文本、等高线及其标签添加描边效果,以及如何为图例添加阴影效果。通过路径效果,你可以创建出视觉上令人惊叹的绘图,以清晰简洁的方式传达你的数据。