使用 Matplotlib 进行自定义网格变换

Beginner

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

简介

本实验提供了一份详细指南,介绍如何使用 GridHelperCurveLinear 通过对网格应用变换来定义自定义网格和刻度线。我们将使用 Python 的 Matplotlib 库来创建自定义网格和刻度线。

虚拟机使用提示

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

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

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

导入所需库

第一步是导入所需的库,包括 matplotlib.pyplotnumpyExtremeFinderSimpleMaxNLocatorGridHelperCurveLinear

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axisartist.axislines import Axes
from mpl_toolkits.axisartist.grid_finder import (ExtremeFinderSimple, MaxNLocator)
from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear

定义变换函数

第二步是定义变换函数。在这个例子中,我们将使用 tr 函数来变换 x 轴的值,而 y 轴的值保持不变。inv_tr 函数将用于反转该变换。

def tr(x, y):
    return np.sign(x)*abs(x)**.5, y

def inv_tr(x, y):
    return np.sign(x)*x**2, y

定义 GridHelperCurveLinear

第三步是定义 GridHelperCurveLinear 实例。我们将使用第二步中定义的变换函数来变换网格。我们还将把 grid_locator1grid_locator2 设置为 MaxNLocator(nbins=6) 以增加刻度密度。

grid_helper = GridHelperCurveLinear(
    (tr, inv_tr),
    extreme_finder=ExtremeFinderSimple(20, 20),
    grid_locator1=MaxNLocator(nbins=6), grid_locator2=MaxNLocator(nbins=6))

定义坐标轴并显示图像

第四步是使用第三步中创建的 grid_helper 实例来定义坐标轴。我们还将使用 imshow 函数显示一幅图像。

ax1 = fig.add_subplot(axes_class=Axes, grid_helper=grid_helper)
ax1.imshow(np.arange(25).reshape(5, 5), vmax=50, cmap=plt.cm.gray_r, origin="lower")

创建图形

最后一步是使用 plt.figure 函数创建图形。我们将把图形大小设置为 (7, 4),并调用在步骤 2 - 4 中创建的 curvelinear_test1 函数。

if __name__ == "__main__":
    fig = plt.figure(figsize=(7, 4))
    curvelinear_test1(fig)
    plt.show()

总结

在本实验中,我们学习了如何通过对网格应用变换,使用 GridHelperCurveLinear 来定义自定义网格和刻度线。我们使用 Python 的 Matplotlib 库为显示在坐标轴上的 5x5 矩阵创建了一个自定义网格和刻度线。