2013-07-17 67 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),这意味着它不能被称为作为一种方法。后者是用于启用/禁用偏移量的方法。