有没有办法检测 Matplotlib 图中的缩放并根据缩放级别设置次刻度格式?

Is there a way to detect zoom in Matplotlib plots and set minor tick format according to zoom level?

我想绘制较大的数据范围,但能够放大并获得分辨率。我需要使用自定义主要和次要刻度格式,因此我无法使用缩放级别动态设置它们。这个问题有实际的解决方案吗?

您只需创建自己的 tick formatter,然后将其附加到 axes 对象。

This 例子有你需要的一切。本质上,创建一个函数,它接受刻度的值,returns 你想要的刻度标签是什么 - 称之为 my_formatter,然后这样做:

ax.xaxis.set_major_formatter(ticker.FuncFormatter(my_formatter))

和可选的

ax.xaxis.set_minor_formatter(ticker.FuncFormatter(my_formatter))

ticker.FuncFormatter(my_function) 为您创建自定义格式化程序的地方。

如果刻度的格式实际上取决于缩放级别,则需要定义一个可以访问轴限制的刻度格式化程序。不幸的是,这不能直接使用 ticker.FuncFormatter 完成,因为传递给构造函数的函数不将轴限制作为参数。 一种访问轴限制的方法是继承 ticker.Formatter 并覆盖 __call__ 方法。

例如,这样的 class 可以定义如下。

import matplotlib.pyplot as plt
from matplotlib.ticker import Formatter

# Custom formatter class
class CustomFormatter(Formatter):
    def __init__(self, ax: Any):
        super().__init__()
        self.set_axis(ax)

    def __call__(self, x, pos=None):
        # Find the axis range
        vmin, vmax = self.axis.get_view_interval()
        # Use the range to define the custom string
        return f"[{vmin:.1f}, {vmax:.1f}]: {x:.1f}"

之后可以通过以下方式使用

formatter = CustomFormatter(ax)
ax.yaxis.set_major_formatter(formatter)

这样,缩放时范围会相应调整。同样,对于次要刻度也可以实现这一点。

完整的测试示例:

data = [1, 4, 2, 7, 4, 6]
ax = plt.gca()
ax.plot(data)
ax.yaxis.set_major_formatter(CustomFormatter(ax))
plt.tight_layout()
plt.show()