注释连接样式

PythonPythonBeginner
立即练习

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

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

简介

本实验将指导你使用 Python 中的 Matplotlib 库创建注释连接样式的过程。注释是数据可视化中的一个重要工具,因为它们有助于解释或突出显示图表上的特定数据点。注释的连接样式是指将注释连接到数据点的线条的形状和样式。

虚拟机提示

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

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

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

导入必要的库

在创建注释之前,我们需要导入必要的库。在这种情况下,我们将使用 Matplotlib 库。

import matplotlib.pyplot as plt

定义用于创建注释连接样式的函数

我们将定义一个函数,该函数接受两个参数:坐标轴对象和连接样式。该函数将绘制两个数据点,并使用指定的连接样式创建一个注释。

def demo_con_style(ax, connectionstyle):
    x1, y1 = 0.3, 0.2
    x2, y2 = 0.8, 0.6

    ax.plot([x1, x2], [y1, y2], ".")
    ax.annotate("",
                xy=(x1, y1), xycoords='data',
                xytext=(x2, y2), textcoords='data',
                arrowprops=dict(arrowstyle="->", color="0.5",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle=connectionstyle,
                                ),
                )

    ax.text(.05,.95, connectionstyle.replace(",", ",\n"),
            transform=ax.transAxes, ha="left", va="top")

创建注释连接样式

我们将使用 demo_con_style 函数创建各种注释连接样式,并将它们绘制在一个网格上。

fig, axs = plt.subplots(3, 5, figsize=(7, 6.3), layout="constrained")
demo_con_style(axs[0, 0], "angle3,angleA=90,angleB=0")
demo_con_style(axs[1, 0], "angle3,angleA=0,angleB=90")
demo_con_style(axs[0, 1], "arc3,rad=0.")
demo_con_style(axs[1, 1], "arc3,rad=0.3")
demo_con_style(axs[2, 1], "arc3,rad=-0.3")
demo_con_style(axs[0, 2], "angle,angleA=-90,angleB=180,rad=0")
demo_con_style(axs[1, 2], "angle,angleA=-90,angleB=180,rad=5")
demo_con_style(axs[2, 2], "angle,angleA=-90,angleB=10,rad=5")
demo_con_style(axs[0, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0")
demo_con_style(axs[1, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5")
demo_con_style(axs[2, 3], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
demo_con_style(axs[0, 4], "bar,fraction=0.3")
demo_con_style(axs[1, 4], "bar,fraction=-0.3")
demo_con_style(axs[2, 4], "bar,angle=180,fraction=-0.2")

for ax in axs.flat:
    ax.set(xlim=(0, 1), ylim=(0, 1.25), xticks=[], yticks=[], aspect=1.25)
fig.set_constrained_layout_pads(wspace=0, hspace=0, w_pad=0, h_pad=0)

plt.show()

解释结果

将显示带有不同连接样式的注释网格。这些注释有助于突出图表上的数据点,不同的样式展示了 Matplotlib 中注释功能的多样性。

总结

本实验概述了如何使用 Python 中的 Matplotlib 库创建注释连接样式。注释是数据可视化中的一个有用工具,可用于解释或突出显示图表上的特定数据点。注释的连接样式是指将注释连接到数据点的线条的形状和样式。通过遵循本实验中概述的步骤,你现在应该能够在 Matplotlib 中创建自己的注释连接样式。