使用 Matplotlib 创建箭头参考图表

PythonPythonBeginner
立即练习

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

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

简介

本教程将指导你使用 Python 中的 Matplotlib 创建一个箭头样式参考图表。该图表将展示 ~.Axes.annotate 中可用的不同箭头样式。

虚拟机使用提示

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

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

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

导入必要的库

导入创建箭头样式参考图表所需的库。

import inspect
import itertools
import re

import matplotlib.pyplot as plt

import matplotlib.patches as mpatches

获取箭头样式

使用 mpatches.ArrowStyle.get_styles() 来获取 ~.Axes.annotate 中可用的所有箭头样式。

styles = mpatches.ArrowStyle.get_styles()

设置图形

使用 plt.figure()add_gridspec() 设置图形。该图形将有一个 2 列和 n 行的网格,其中 n 是箭头样式的数量。网格中的每个单元格将包含一种箭头样式及其默认参数。

ncol = 2
nrow = (len(styles) + 1) // ncol
axs = (plt.figure(figsize=(4 * ncol, 1 + nrow))
     .add_gridspec(1 + nrow, ncol,
                    wspace=.7, left=.1, right=.9, bottom=0, top=1).subplots())
for ax in axs.flat:
    ax.set_axis_off()
for ax in axs[0, :]:
    ax.text(0,.5, "arrowstyle",
            transform=ax.transAxes, size="large", color="tab:blue",
            horizontalalignment="center", verticalalignment="center")
    ax.text(.35,.5, "default parameters",
            transform=ax.transAxes,
            horizontalalignment="left", verticalalignment="center")

绘制箭头样式

在网格的每个单元格中绘制每种箭头样式及其默认参数。使用 ax.annotate() 将箭头样式名称及其默认参数添加到单元格中。

for ax, (stylename, stylecls) in zip(axs[1:, :].T.flat, styles.items()):
    l, = ax.plot(.25,.5, "ok", transform=ax.transAxes)
    ax.annotate(stylename, (.25,.5), (-0.1,.5),
                xycoords="axes fraction", textcoords="axes fraction",
                size="large", color="tab:blue",
                horizontalalignment="center", verticalalignment="center",
                arrowprops=dict(
                    arrowstyle=stylename, connectionstyle="arc3,rad=-0.05",
                    color="k", shrinkA=5, shrinkB=5, patchB=l,
                ),
                bbox=dict(boxstyle="square", fc="w"))
    ## wrap at every nth comma (n = 1 or 2, depending on text length)
    s = str(inspect.signature(stylecls))[1:-1]
    n = 2 if s.count(',') > 3 else 1
    ax.text(.35,.5,
            re.sub(', ', lambda m, c=itertools.count(1): m.group()
                   if next(c) % n else '\n', s),
            transform=ax.transAxes,
            horizontalalignment="left", verticalalignment="center")

显示图表

使用 plt.show() 显示箭头样式参考图表。

plt.show()

总结

在本教程中,你学习了如何使用 Python 中的 Matplotlib 创建一个箭头样式参考图表。你使用 mpatches.ArrowStyle.get_styles() 来获取 ~.Axes.annotate 中可用的所有箭头样式,使用 plt.figure()add_gridspec() 设置图形,在网格的每个单元格中绘制每种箭头样式,并使用 plt.show() 显示图表。