防止科学计数法

142

我有以下代码:

plt.plot(range(2003,2012,1),range(200300,201200,100))
# several solutions from other questions have not worked, including
# plt.ticklabel_format(style='sci', axis='x', scilimits=(-1000000,1000000))
# ax.get_xaxis().get_major_formatter().set_useOffset(False)
plt.show()

这将生成以下图表:

plot

我该如何防止科学计数法?Is ticklabel_format broken?不能真正解决消除偏移量的问题。

plt.plot(np.arange(1e6, 3 * 1e7, 1e6))
plt.ticklabel_format(useOffset=False)

enter image description here

3个回答

234

在您的情况下,实际上您想要禁用偏移量。使用科学计数法是与以偏移值显示内容的设置不同的设置。

但是,ax.ticklabel_format(useOffset=False) 应该可以工作(尽管您已将其列为未奏效的事物之一)。

例如:

fig, ax = plt.subplots()
ax.plot(range(2003,2012,1),range(200300,201200,100))
ax.ticklabel_format(useOffset=False)
plt.show()

这里输入图片描述

如果您想同时禁用偏移量和科学计数法,可以使用ax.ticklabel_format(useOffset=False, style='plain')


"偏移量"和"科学计数法"之间的区别

在 Matplotlib 坐标轴格式化中,“科学计数法”是指所显示数字的乘数,而“偏移量”是一个单独的值,需要被加上

考虑下面这个例子:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1000, 1001, 100)
y = np.linspace(1e-9, 1e9, 100)

fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

x轴会有一个偏移量(请注意 + 符号),而y轴将使用科学计数法(作为乘数 -- 没有加号)。

enter image description here

我们可以分别禁用其中一个。最方便的方法是使用 ax.ticklabel_format 方法(或 plt.ticklabel_format)。

例如,如果我们调用:

ax.ticklabel_format(style='plain')

我们将禁用y轴上的科学计数法:

enter image description here

如果我们调用

ax.ticklabel_format(useOffset=False)

我们将禁用X轴上的偏移量,但保留Y轴科学计数法:

enter image description here

最后,我们可以通过以下方式同时禁用两者:

ax.ticklabel_format(useOffset=False, style='plain')

图片描述


2

另一种防止科学计数法的方法是使用scilimits=参数“扩大”不使用科学计数法的区间。

plt.plot(np.arange(1e6, 3 * 1e7, 1e6))
plt.ticklabel_format(scilimits=(-5, 8))

result1

在此处,如果轴限制小于10^-5或大于10^8,则使用科学计数法。

默认情况下,对 小于10^-5或大于10^6 的数字使用科学计数法,因此如果刻度的最高值在此间隔内,则不使用科学计数法。

因此,绘制的图形为

plt.plot(np.arange(50), np.logspace(0, 6));
plt.ylim((0, 1000000))

出现科学计数法是因为1000000=10^6,但由此创建的图表

plt.plot(np.arange(50), np.logspace(0, 6));
plt.ylim((0, 999999));

这是因为y轴的限制(999999)比默认限制10^6要小。

可以通过使用ticklabel_format()scilimits=参数来更改此默认限制;只需传递格式为(low, high)的元组,其中刻度的上限应在区间(10^low, 10^high)内。例如,在以下代码中(一个有点极端的例子),刻度显示为完整数字,因为np.logspace(0,100)[-1] < 10**101为True。

plt.plot(np.logspace(0, 8), np.logspace(0, 100));
plt.ticklabel_format(scilimits=(0, 101))

result2


2
您可以全局禁用所有图表的此功能。
    # Disable scientific notation on axes
    # by setting the threshold exponent very high
    matplotlib.rcParams["axes.formatter.limits"] = (-99, 99)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接