python-2.7 - 如何使用 matplotlib 设置偏移量

标签 python-2.7 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)

没有任何成功(结果不变)。 难道我做错了什么?我怎样才能改变这种行为?或者我必须手动设置刻度线?

预先感谢您的帮助!

最佳答案

您可以使用FuncFormatterticker 模块中根据需要格式化刻度标签:

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) 来禁用此行为。然后数字将显示为小数。

偏移是您必须添加(或减去)到刻度值的值,而不是,因为后者是一个规模

供引用,该行

MyFormatter.useOffset(False)

应该是

MyFormatter.set_useOffset(False)

因为第一个是 bool (只能有值 TrueFalse),这意味着它不能被称为一个方法。后者是用于启用/禁用偏移的方法。

关于python-2.7 - 如何使用 matplotlib 设置偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17695145/

相关文章:

从文本文件读取时的 Python 编码问题

Python Pandas : Selecting previous row of matching row

python - 使用 css 样式从网站抓取数据 使用 Beautifulsoup

python - 在 Windows 上使用 PyCharm 的 matplotlib 不会绘制图形,没有错误

python - 在用 python 问题编写的 qt 应用程序中缩放嵌入式 matplotlib 小部件

python - 如何在标签中绘制带有汉字的图形

macos - 无法在 Mac OS X 上安装 scipy

python - 段错误(核心已转储)。在 python 中使用 C 模块

python - 如何绘制多个图形并使用 [matplotlib] 中的导航按钮

python - 在 matplotlib 图上禁用工具栏上的像素值