防止科学计数法

问题描述 投票:0回答:3

我有以下代码:

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

如何在这里阻止科学记数法? ticklabel_format 是否损坏? 无法解决实际删除偏移量的问题。

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

python matplotlib plot scientific-notation
3个回答
227
投票

就您而言,您实际上想要禁用偏移。使用科学记数法是与用偏移值显示事物不同的设置。

但是,

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()

enter image description here

如果您想禁用偏移量和科学计数法,您可以使用

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')

enter image description here


1
投票

防止科学记数法的另一种方法是使用

scilimits=
参数“扩大”不使用科学记数法的区间。

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

这里,如果轴限制小于 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。

可以使用

scilimits=

ticklabel_format()
 参数更改此默认限制;只需传递格式为 
(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))


0
投票
您可以通过

对所有图表全局禁用此功能

# Disable scientific notation on axes # by setting the threshold exponent very high matplotlib.rcParams["axes.formatter.limits"] = (-99, 99)
    
© www.soinside.com 2019 - 2024. All rights reserved.