将轴偏移值格式化为整数或特定数字

2025-02-11 09:50:00
admin
原创
46
摘要:问题描述:我有一个 matplotlib 图,其中绘制的数据始终以纳秒 (1e-9) 为单位。在 y 轴上,如果我有几十纳秒的数据,即 44e-9,则轴上的值显示为 4.4,偏移量为 +1e-8。有没有办法强制轴显示 44,偏移量为 +1e-9?我的 x 轴也是如此,轴显示 +5.54478e4,我宁愿显示偏...

问题描述:

我有一个 matplotlib 图,其中绘制的数据始终以纳秒 (1e-9) 为单位。在 y 轴上,如果我有几十纳秒的数据,即 44e-9,则轴上的值显示为 4.4,偏移量为 +1e-8。有没有办法强制轴显示 44,偏移量为 +1e-9?

我的 x 轴也是如此,轴显示 +5.54478e4,我宁愿显示偏移量 +55447(整数,无小数 - 这里的值以天为单位)。

我尝试过这样的几件事:

p = axes.plot(x,y)
p.ticklabel_format(style='plain')

对于 x 轴,但这不起作用,虽然我可能使用不当或误解了文档中的某些内容,有人可以指出我正确的方向吗?

谢谢,乔纳森

问题说明


我尝试使用格式化程序做一些事情,但还没有找到任何解决方案......:

myyfmt = ScalarFormatter(useOffset=True)
myyfmt._set_offset(1e9)
axes.get_yaxis().set_major_formatter(myyfmt)

myxfmt = ScalarFormatter(useOffset=True)
myxfmt.set_portlimits((-9,5))
axes.get_xaxis().set_major_formatter(myxfmt)

顺便说一句,我实际上对“偏移量数”对象的实际位置感到困惑...它是主/次刻度的一部分吗?


解决方案 1:

我遇到了完全相同的问题,并且这些行解决了该问题:

from matplotlib.ticker import ScalarFormatter

y_formatter = ScalarFormatter(useOffset=False)
ax.yaxis.set_major_formatter(y_formatter)

解决方案 2:

一个更简单的解决方案是简单地自定义刻度标签。请看以下示例:

from pylab import *

# Generate some random data...
x = linspace(55478, 55486, 100)
y = random(100) - 0.5
y = cumsum(y)
y -= y.min()
y *= 1e-8

# plot
plot(x,y)

# xticks
locs,labels = xticks()
xticks(locs, map(lambda x: "%g" % x, locs))

# ytikcs
locs,labels = yticks()
yticks(locs, map(lambda x: "%.1f" % x, locs*1e9))
ylabel('microseconds (1E-9)')

show()

替代文本

注意,在 y 轴的情况下,我将值乘以,1e9然后在 y 标签中提到该常数


编辑

另一种选择是通过手动将其文本添加到图的顶部来伪造指数乘数:

locs,labels = yticks()
yticks(locs, map(lambda x: "%.1f" % x, locs*1e9))
text(0.0, 1.01, '1e-9', fontsize=10, transform = gca().transAxes)

编辑2

您也可以用同样的方式格式化 x 轴偏移值:

locs,labels = xticks()
xticks(locs, map(lambda x: "%g" % x, locs-min(locs)))
text(0.92, -0.07, "+%g" % min(locs), fontsize=10, transform = gca().transAxes)

替代文本

解决方案 3:

您必须子类化ScalarFormatter才能执行所需的操作……_set_offset只需添加一个常数,即可设置ScalarFormatter.orderOfMagnitude。不幸的是,手动设置orderOfMagnitude不会做任何事情,因为在ScalarFormatter调用实例来格式化轴刻度标签时会重置它。它不应该这么复杂,但我找不到更简单的方法来做你想做的事……这是一个例子:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, FormatStrFormatter

class FixedOrderFormatter(ScalarFormatter):
    """Formats axis ticks using scientific notation with a constant order of 
    magnitude"""
    def __init__(self, order_of_mag=0, useOffset=True, useMathText=False):
        self._order_of_mag = order_of_mag
        ScalarFormatter.__init__(self, useOffset=useOffset, 
                                 useMathText=useMathText)
    def _set_orderOfMagnitude(self, range):
        """Over-riding this to avoid having orderOfMagnitude reset elsewhere"""
        self.orderOfMagnitude = self._order_of_mag

# Generate some random data...
x = np.linspace(55478, 55486, 100) 
y = np.random.random(100) - 0.5
y = np.cumsum(y)
y -= y.min()
y *= 1e-8

# Plot the data...
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'b-')

# Force the y-axis ticks to use 1e-9 as a base exponent 
ax.yaxis.set_major_formatter(FixedOrderFormatter(-9))

# Make the x-axis ticks formatted to 0 decimal places
ax.xaxis.set_major_formatter(FormatStrFormatter('%0.0f'))
plt.show()

结果如下:
替代文本

而默认格式如下:
替代文本

希望这能有点帮助!

编辑:不管怎么说,我也不知道偏移标签在哪里……手动设置它会稍微容易一些,但我不知道该怎么做……我觉得一定有比所有这些更简单的方法。不过,它确实有效!

解决方案 4:

与 Amro 的答案类似,您可以使用 FuncFormatter

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

# Generate some random data...
x = np.linspace(55478, 55486, 100) 
y = np.random.random(100) - 0.5
y = np.cumsum(y)
y -= y.min()
y *= 1e-8

# Plot the data...
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'b-')

# Force the y-axis ticks to use 1e-9 as a base exponent 
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: ('%.1f')%(x*1e9)))
ax.set_ylabel('microseconds (1E-9)')

# Make the x-axis ticks formatted to 0 decimal places
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%.0f'%x))
plt.show()

解决方案 5:

在添加以下内容后,Gonzalo 的解决方案开始为我工作set_scientific(False)

ax=gca()
fmt=matplotlib.ticker.ScalarFormatter(useOffset=False)
fmt.set_scientific(False)
ax.xaxis.set_major_formatter(fmt)

解决方案 6:

正如评论和这个答案中指出的那样,可以通过执行以下操作来全局关闭偏移量:

matplotlib.rcParams['axes.formatter.useoffset'] = False

解决方案 7:

我认为更优雅的方法是使用 ticker 格式化程序。以下是 xaxis 和 yaxis 的示例:

from pylab import *
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

majorLocator   = MultipleLocator(20)
xFormatter = FormatStrFormatter('%d')
yFormatter = FormatStrFormatter('%.2f')
minorLocator   = MultipleLocator(5)


t = arange(0.0, 100.0, 0.1)
s = sin(0.1*pi*t)*exp(-t*0.01)

ax = subplot(111)
plot(t,s)

ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(xFormatter)
ax.yaxis.set_major_formatter(yFormatter)

#for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(minorLocator)

解决方案 8:

对于第二部分,无需再次手动重置所有刻度,这是我的解决方案:

class CustomScalarFormatter(ScalarFormatter):
    def format_data(self, value):
        if self._useLocale:
            s = locale.format_string('%1.2g', (value,))
        else:
            s = '%1.2g' % value
        s = self._formatSciNotation(s)
        return self.fix_minus(s)
xmajorformatter = CustomScalarFormatter()  # default useOffset=True
axes.get_xaxis().set_major_formatter(xmajorformatter)

显然,您可以将格式字符串设置为任何您想要的。

解决方案 9:

Joe Kington 的答案对我来说似乎不起作用。但我发现 matplotlib 现在可以使用set_powerlimits原生地执行此操作:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

# Generate some random data...
x = np.linspace(55478, 55486, 100) 
y = np.random.random(100) - 0.5
y = np.cumsum(y)
y -= y.min()
y *= 1e-8

# Plot the data...
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'b-')

# Force the y-axis ticks to use 1e-9 as a base exponent
y_formatter = ScalarFormatter()
y_formatter.set_powerlimits((-9, -9))
ax.yaxis.set_major_formatter(y_formatter)

# Make the x-axis ticks formatted to 0 decimal places
ax.xaxis.set_major_formatter(ScalarFormatter(useOffset=False))
plt.show()
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用