Matplotlib 文本旋转

PythonPythonBeginner
立即练习

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

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

简介

在本实验中,你将学习如何使用 rotation_mode 参数在 Matplotlib 中旋转文本。rotation_mode 参数决定了文本旋转和对齐的顺序。有两种可用模式:defaultanchor

虚拟机提示

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

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

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

导入必要的库

首先,我们需要导入必要的库。在本实验中,我们将使用 Matplotlib 来创建图表。

import matplotlib.pyplot as plt

定义 test_rotation_mode 函数

我们将创建一个名为 test_rotation_mode 的函数,该函数将创建子图以测试不同的旋转模式。它接受两个参数:figmode

def test_rotation_mode(fig, mode):

定义水平和垂直对齐列表

接下来,我们将定义用于创建子图的水平和垂直对齐列表。我们将为每个列表创建三个元素:水平对齐的 "left"(左对齐)、"center"(居中对齐)和 "right"(右对齐),以及垂直对齐的 "top"(顶部对齐)、"center"(居中对齐)和 "bottom"(底部对齐)。

ha_list = ["left", "center", "right"]
va_list = ["top", "center", "baseline", "bottom"]

创建子图

现在,我们将使用 subplots 函数创建子图。我们将创建一个具有相同纵横比的子图网格,并去除 x 轴和 y 轴上的刻度。我们还将在每个子图的中心添加一条垂直线和一条水平线,以帮助直观地显示对齐方式。

axs = fig.subplots(len(va_list), len(ha_list), sharex=True, sharey=True,
                   subplot_kw=dict(aspect=1),
                   gridspec_kw=dict(hspace=0, wspace=0))

for i, va in enumerate(va_list):
    for j, ha in enumerate(ha_list):
        ax = axs[i, j]
        ax.set(xticks=[], yticks=[])
        ax.axvline(0.5, color="skyblue", zorder=0)
        ax.axhline(0.5, color="skyblue", zorder=0)
        ax.plot(0.5, 0.5, color="C0", marker="o", zorder=1)

向子图添加文本

我们将使用 text 函数向每个子图添加文本。我们将使用参数 rotation(旋转)、horizontalalignment(水平对齐)、verticalalignment(垂直对齐)和 rotation_mode(旋转模式)来旋转和对齐文本。我们还将使用 bbox 参数来突出显示文本的边界框。

kw = (
    {} if mode == "default" else
    {"bbox": dict(boxstyle="square,pad=0.", ec="none", fc="C1", alpha=0.3)}
)

texts = {}

for i, va in enumerate(va_list):
    for j, ha in enumerate(ha_list):
        ax = axs[i, j]
        tx = ax.text(0.5, 0.5, "Tpg",
                     size="x-large", rotation=40,
                     horizontalalignment=ha, verticalalignment=va,
                     rotation_mode=mode, **kw)
        texts[ax] = tx

突出显示文本的边界框

如果 rotation_mode 设置为 'default',我们将使用一个矩形来突出显示文本的边界框。我们将使用 get_window_extent 函数获取边界框,并使用 transData 属性将其转换为数据坐标。

if mode == "default":
    fig.canvas.draw()
    for ax, text in texts.items():
        bb = text.get_window_extent().transformed(ax.transData.inverted())
        rect = plt.Rectangle((bb.x0, bb.y0), bb.width, bb.height,
                             facecolor="C1", alpha=0.3, zorder=2)
        ax.add_patch(rect)

创建子图并调用 test_rotation_mode 函数

我们将创建两个子图,并使用 figmode 参数调用 test_rotation_mode 函数。

fig = plt.figure(figsize=(8, 5))
subfigs = fig.subfigures(1, 2)
test_rotation_mode(subfigs[0], "default")
test_rotation_mode(subfigs[1], "anchor")
plt.show()

总结

在本实验中,我们学习了如何使用 rotation_mode 参数在 Matplotlib 中旋转文本。我们创建了一个名为 test_rotation_mode 的函数,该函数创建子图以测试不同的旋转模式。我们定义了水平和垂直对齐列表,创建了子图,向子图中添加了文本,并突出显示了文本的边界框。最后,我们创建了子图并调用了 test_rotation_mode 函数。