在 Matplotlib 中更改轴的方向

Beginner

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

简介

在本实验中,你将学习如何使用 set_axis_direction() 方法更改 Matplotlib 绘图中的轴方向。此方法允许你将轴的方向更改为四个基本方向中的任何一个:顶部、底部、左侧或右侧。

虚拟机提示

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

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

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

导入库

首先,我们需要为本实验导入必要的库。我们将使用 numpymatplotlib

import matplotlib.pyplot as plt
import numpy as np

设置绘图

接下来,我们将定义一个函数 setup_axes(),该函数将在一个矩形框中设置极坐标投影。此函数使用 GridHelperCurveLinear 创建一个带有矩形框的极坐标投影。

from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist as axisartist
import mpl_toolkits.axisartist.angle_helper as angle_helper
import mpl_toolkits.axisartist.grid_finder as grid_finder
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
    GridHelperCurveLinear

def setup_axes(fig, rect):
    """极坐标投影,但在一个矩形框中。"""
    grid_helper = GridHelperCurveLinear(
        Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform(),
        extreme_finder=angle_helper.ExtremeFinderCycle(
            20, 20,
            lon_cycle=360, lat_cycle=None,
            lon_minmax=None, lat_minmax=(0, np.inf),
        ),
        grid_locator1=angle_helper.LocatorDMS(12),
        grid_locator2=grid_finder.MaxNLocator(5),
        tick_formatter1=angle_helper.FormatterDMS(),
    )
    ax = fig.add_subplot(
        rect, axes_class=axisartist.Axes, grid_helper=grid_helper,
        aspect=1, xlim=(-5, 12), ylim=(-5, 10))
    ax.axis[:].toggle(ticklabels=False)
    ax.grid(color=".9")
    return ax

添加浮动轴

我们将定义两个函数,用于向绘图中添加浮动轴。第一个函数 add_floating_axis1() 向绘图中添加一个标签为 theta = 30 的浮动轴。第二个函数 add_floating_axis2() 向绘图中添加一个标签为 r = 6 的浮动轴。

def add_floating_axis1(ax):
    ax.axis["lat"] = axis = ax.new_floating_axis(0, 30)
    axis.label.set_text(r"$\theta = 30^{\circ}$")
    axis.label.set_visible(True)
    return axis

def add_floating_axis2(ax):
    ax.axis["lon"] = axis = ax.new_floating_axis(1, 6)
    axis.label.set_text(r"$r = 6$")
    axis.label.set_visible(True)
    return axis

更改轴的方向

现在,我们将创建一个循环,以设置四个不同的绘图,每个绘图中的浮动轴位于四个基本方向中的一个。在循环中,我们将使用 add_floating_axis1()add_floating_axis2() 添加浮动轴,并使用 set_axis_direction() 设置轴的方向。

fig = plt.figure(figsize=(8, 4), layout="constrained")

for i, d in enumerate(["bottom", "left", "top", "right"]):
    ax = setup_axes(fig, rect=241+i)
    axis = add_floating_axis1(ax)
    axis.set_axis_direction(d)
    ax.set(title=d)

for i, d in enumerate(["bottom", "left", "top", "right"]):
    ax = setup_axes(fig, rect=245+i)
    axis = add_floating_axis2(ax)
    axis.set_axis_direction(d)
    ax.set(title=d)

plt.show()

查看绘图

最后,我们将查看绘图。我们可以看到在四个基本方向上都带有浮动轴的相同绘图。

总结

在本实验中,你学习了如何使用 set_axis_direction() 方法在 Matplotlib 绘图中更改轴的方向。通过使用此方法,你可以轻松地将轴的方向更改为四个基本方向中的任何一个:顶部、底部、左侧或右侧。