2011-11-30 264 views
1

在Matplotlib中,我想使用y轴的FunctionFormatter格式化坐标图,以便在靠近图底部的区域不显示任何刻度。这是制作一个“无数据”区域,即沿着图底部的一条带,其中没有y值的数据将被绘制。Matplotlib:使用显示坐标的自定义坐标轴格式化程序

伪代码,该功能会是这样:

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

Formatter与显示滴答无关,它只控制滴答标签的格式。你需要修改Locator,它可以找到显示的刻度位置。

有2种方式来完成任务:

  • 写自己的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