【问题标题】:How to remove scientific notation on a matplotlib log-log plot如何在 matplotlib 对数图上删除科学记数法
【发布时间】:2018-09-19 20:45:54
【问题描述】:

我知道以前有人问过这个问题,但我尝试了所有可能的解决方案,但没有一个对我有用。

所以,我在 matplotlib 中有一个对数图,我想避免在 x 轴上使用科学记数法。

这是我的代码:

from numpy import array, log, pi
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import matplotlib.ticker as mticker

plt.rc('axes.formatter', useoffset=False)

tc = array([7499680.0, 12508380.0, 23858280.0, 34877020.0, 53970660.0, 89248580.0, 161032860.0, 326814160.0, 784460200.0])

theta = array([70, 60, 50, 45, 40, 35, 30, 25, 20])

plt.scatter(theta,tc)

ax=plt.gca()

ax.set_xscale('log')
ax.set_yscale('log')

ax.xaxis.set_major_formatter(mticker.ScalarFormatter())
ax.xaxis.get_major_formatter().set_scientific(False)
ax.xaxis.get_major_formatter().set_useOffset(False)

plt.show()

这是输出:

如您所见,x 轴上的数字仍然是科学计数法。我想将它们显示为 20、30、40... 我尝试了所有可能的解决方案,但没有结果。

非常感谢所有愿意提供帮助的人。

注意。我不能使用 plt.loglog() 命令,因为我正在对数据进行一些曲线拟合,我需要它。

NB2。我注意到发生了一件非常奇怪的事情:如果我将代码更改为 yaxis.get_mayor_formatter()...,它会在 y 轴上运行!只是在 x 上它不起作用。怎么可能?

编辑:也许不清楚,但如果你看一下代码,有 3 种方法会影响 x-ticks 的显示:plt.rc('axes.formatter', useoffset=False)ax.xaxis.set_major_formatter(mticker.ScalarFormatter())ax.xaxis.get_major_formatter().set_scientific(False)。根据我发现的情况,它们是 3 种方法都应该单独解决问题,但事实并非如此。当然,我也一一尝试过,而不是一起尝试。

【问题讨论】:

    标签: python matplotlib plot notation


    【解决方案1】:

    这些是 x 轴上的次要刻度(即它们不是 10 的整数次幂),而不是主要刻度。 matplotlib 自动确定它是否应该标记主要或次要刻度 - 在这种情况下,因为您没有在 x 范围内显示任何主要刻度,所以正在标记次要刻度)。所以,你需要使用set_minor_formatter 方法:

    ax.xaxis.set_minor_formatter(mticker.ScalarFormatter())
    

    它在 y 轴上起作用的原因是因为这些刻度是主要刻度(即 10 的整数幂),而不是次要刻度。

    【讨论】:

    【解决方案2】:

    以下可用作解决方法 (original answer):

    from matplotlib.ticker import StrMethodFormatter, NullFormatter
    ax.yaxis.set_major_formatter(StrMethodFormatter('{x:.0f}'))
    ax.yaxis.set_minor_formatter(NullFormatter())
    

    【讨论】:

      【解决方案3】:

      如果您只想将 xaxis 设置为不再使用科学记数法,则需要更改 fromatter,然后您可以将其设置为 plain。

      ax.xaxis.set_minor_formatter(mticker.ScalarFormatter())
      ax.ticklabel_format(style='plain', axis='x')
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

        • 不起作用。我收到一个错误:“AttributeError:此方法仅适用于 ScalarFormatter”。
        • 你用的很奇怪
        • 是的,我知道。这就是我问这个问题的原因。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-04
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        相关资源
        最近更新 更多