2011-11-30 262 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