Matplotlib:使用显示坐标的自定义轴格式化程序

2024-10-04 11:26:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在Matplotlib中,我想对y轴使用FunctionFormatter来格式化记号,这样就不会在绘图底部附近的区域显示记号。这是为了创建一个“y数据较少”区域,即沿着绘图底部的一条带,其中将绘制没有y值的数据。在

在伪代码中,该函数如下所示:

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

或者

^{pr2}$

我肯定我得用倒装轴.transData.transform但我不知道该怎么做。在

如果重要的话,我还将提到:在这个格式化程序中我还有其他格式化规则,处理有y数据的绘图部分。在


Tags: of数据函数代码self区域绘图if
1条回答
网友
1楼 · 发布于 2024-10-04 11:26:39

Formatter与显示刻度无关,它只控制刻度标签的格式。您需要的是修改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

相关问题 更多 >