Matplotlib:使用显示坐标自定义轴格式化器

1 投票
1 回答
1403 浏览
提问于 2025-04-17 07:25

在Matplotlib中,我想为y轴使用一个函数格式化器,这样可以让图表底部附近的刻度不显示。这样做是为了在图表底部留出一个“没有y数据”的区域,方便在这里绘制没有y值的数据。

用伪代码来说,这个函数大概是这样的:

def CustomFormatter(self,y,i):
        if y falls in the bottom 50 pixels' worth of height of this plot:
            return ''

或者

def CustomFormatter(self,y,i):
        if y falls in the bottom 10% of the height of this plot in display coordinates:
            return ''

我觉得我需要使用反转的axes.transData.transform来实现这个功能,但我不太确定具体该怎么做。

如果有帮助的话,我还想提一下:我在这个格式化器中还会有其他的格式化规则,处理图表中有y数据的部分。

1 个回答

1

Formatter 和显示刻度(ticks)没有关系,它只负责刻度标签的格式化。你需要的是修改过的 Locator,它负责确定显示的刻度位置。

有两种方法可以完成这个任务:

  • 自己写一个 Locator 类,继承自 matplotlib.ticker.Locator。不过,遗憾的是,关于它的工作原理的文档很少,所以我一直没能做到这一点;

  • 尝试使用预定义的定位器来实现你想要的效果。比如,你可以从图表中获取刻度位置,找到靠近底部的位置,然后用 FixedLocator 替换掉默认的定位器,只保留你需要的刻度。

这里有个简单的例子:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr

x = np.linspace(0,10,501)
y = x * np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)

ticks = ax.yaxis.get_ticklocs()      # get tick locations in data coordinates
lims = ax.yaxis.get_view_interval()  # get view limits
tickaxes = (ticks - lims[0]) / (lims[1] - lims[0])  # tick locations in axes coordinates
ticks = ticks[tickaxes > 0.5] # ticks in upper half of axes
ax.yaxis.set_major_locator(tkr.FixedLocator(ticks))  # override major locator 

plt.show()

这样就会得到如下图表:enter image description here

撰写回答