Python 中带注释的 Matplotlib 图表

PythonPythonBeginner
立即练习

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

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

简介

本教程将指导你使用 Python 中的 Matplotlib 创建带有注释的图表。你将学习如何用箭头连接两个点、在图表中添加椭圆,以及自定义箭头样式和椭圆属性。

虚拟机使用提示

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

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

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

设置图表

首先,我们需要设置一个包含两个子图的图表。我们将使用 subplots 函数创建一个 2x2 的子图网格,然后定义两个点的 x 和 y 坐标。

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

fig, axs = plt.subplots(2, 2)
x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7

用箭头连接两个点

在这一步中,我们将用箭头连接这两个点。我们将使用 annotate 函数来创建箭头,并自定义箭头的样式和颜色。

ax = axs.flat[0]
ax.plot([x1, x2], [y1, y2], ".")
ax.annotate("",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                            color="0.5",
                            connectionstyle="arc3,rad=0.3",
                            ),
            )

在图表中添加椭圆

在这一步中,我们将在图表中添加一个椭圆。我们将使用 Ellipse 函数来创建椭圆,并自定义椭圆的属性,如位置、宽度、高度和角度。

ax = axs.flat[1]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)

自定义箭头以连接到椭圆

在这一步中,我们将自定义箭头以连接到椭圆。我们将使用 arrowprops 参数来指定箭头应连接到椭圆,并且我们还将自定义箭头的样式和颜色。

ax = axs.flat[2]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                            color="0.5",
                            patchB=el,
                            connectionstyle="arc3,rad=0.3",
                            ),
            )

自定义箭头以向椭圆收缩

在这一步中,我们将自定义箭头使其向椭圆收缩。我们将使用 shrinkB 参数来指定箭头向椭圆收缩的量。

ax = axs.flat[3]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='data',
            arrowprops=dict(arrowstyle="fancy",
                            color="0.5",
                            patchB=el,
                            shrinkB=5,
                            connectionstyle="arc3,rad=0.3",
                            ),
            )

总结

在本教程中,你学习了如何使用 Python 中的 Matplotlib 创建带有注释的图表。你学习了如何用箭头连接两个点、在图表中添加椭圆以及自定义箭头样式和椭圆属性。这些技能在创建用于数据可视化的信息丰富且视觉上吸引人的图表时会很有用。