2013-07-17 68 views
0

我想要移除matplotlib自動放置在我的圖上的偏移量。例如,用下面的代碼:如何使用matplotlib設置偏移

x=np.array([1., 2., 3.]) 
y=2.*x*1.e7 
MyFig = plt.figure() 
MyAx = MyFig.add_subplot(111) 
MyAx.plot(x,y) 

我獲得以下結果(對不起,我不能發佈圖像):y軸具有蜱2,2.5%,3,...,6,與y軸頂部的獨特「x10^7」。

我想從軸的頂部刪除「x10^7」,並使其出現在每個刻度(2x10^7,2.5x10^7等)中。如果我能很好地理解我在其他主題中看到的內容,則必須使用use_Offset變量。所以我嘗試了以下事情:

MyFormatter = MyAx.axes.yaxis.get_major_formatter() 
MyFormatter.useOffset(False) 
MyAx.axes.yaxis.set_major_formatter(MyFormatter) 

沒有任何成功(結果不變)。 我做錯了什麼?我怎樣才能改變這種行爲?或者讓我手動設置刻度?

提前感謝您的幫助!

+0

您能否將鏈接發佈到您找到的其他主題?就我個人而言,我認爲你會更好地重新調整軸並將其包含在軸標籤中。 – Greg

+1

您可以手動定義軸刻度。看看[這個答案](http://stackoverflow.com/questions/17426283/axis-labelling-with-matplotlib-too-sparse/17426515#17426515)或[this one](http://stackoverflow.com/questions/16529038/matplotlib-tick-axis-notation-with-superscript/16530841#16530841) – ala

+0

好的,謝謝你的回答。當我需要特定的格式時,我會手動設置它們! – user1618164

回答

0

您可以使用FuncFormatterticker模塊到ticklabels格式化,請你:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.ticker import FuncFormatter 

x=np.array([1., 2., 3.]) 
y=2.*x*1.e7 

MyFig = plt.figure() 
MyAx = MyFig.add_subplot(111) 

def sci_notation(x, pos): 
    return "${:.1f} \\times 10^{{6}}$".format(x/1.e7) 

MyFormatter = FuncFormatter(sci_notation) 

MyAx.axes.yaxis.set_major_formatter(MyFormatter) 

MyAx.plot(x,y) 

plt.show() 

enter image description here


在一個側面說明;顯示在軸上的「x10^7」值不是偏移量,而是科學記數法中使用的一個因子。通過調用MyFormatter.use_scientific(False)可以禁用此行爲。數字將顯示爲小數。

一種偏移是你必須值添加(或減去)到tickvalues而非乘法用,因爲後者是一個規模

作爲參考,線

MyFormatter.useOffset(False) 

應該是

MyFormatter.set_useOffset(False) 

作爲第一個是bool(只能具有值TrueFalse),這意味着它不能被稱爲作爲一種方法。後者是用於啓用/禁用偏移量的方法。