我正在尝试删除 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)
没有任何成功(结果不变)。 难道我做错了什么?我怎样才能改变这种行为?或者我必须手动设置刻度线?
预先感谢您的帮助!
最佳答案
您可以使用FuncFormatter
从 ticker
模块中根据需要格式化刻度标签:
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()
附注;轴顶部出现的“x10^7”值不是偏移量,而是科学记数法中使用的因子。可以通过调用 MyFormatter.use_scientific(False) 来禁用此行为。然后数字将显示为小数。
偏移是您必须添加(或减去)到刻度值的值,而不是乘,因为后者是一个规模。
供引用,该行
MyFormatter.useOffset(False)
应该是
MyFormatter.set_useOffset(False)
因为第一个是 bool
(只能有值 True
或 False
),这意味着它不能被称为一个方法。后者是用于启用/禁用偏移的方法。
关于python-2.7 - 如何使用 matplotlib 设置偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17695145/