【问题标题】:Displaying numbers with "X" instead of "e" scientific notation in matplotlib在 matplotlib 中用“X”而不是“e”科学记数法显示数字
【发布时间】:2015-07-16 11:54:04
【问题描述】:

使用 matplotlib,我想在我的绘图上编写以正常科学计数法显示的文本,例如 1.92x10-7 而不是默认的 1.92e-7。我找到了有关如何为轴上的数字标记刻度而不是文本函数的帮助。这是我想更改的代码示例:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,0.5)
y = x*(1.0-x)

a=1.92e-7

plt.figure()
plt.plot(x, y)
plt.text(0.01, 0.23, r"$a = {0:0.2e}$".format(a), size=20)
plt.show()

【问题讨论】:

  • 第一个想法是过滤函数,它转换格式方法的输出。这已经足够了吗?如果还不够,为什么?否则:严格的科学记数法将是一个中间点而不是“x”......

标签: python matplotlib


【解决方案1】:

这样做的一个稍微笨拙的方法是从它的 Python 字符串表示中为数字构建你自己的 tex 字符串。通过as_si,定义如下,你的数字和小数位数,它将产生这个tex字符串:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,0.5)
y = x*(1.0-x)

def as_si(x, ndp):
    s = '{x:0.{ndp:d}e}'.format(x=x, ndp=ndp)
    m, e = s.split('e')
    return r'{m:s}\times 10^{{{e:d}}}'.format(m=m, e=int(e))

a=1.92e-7

plt.figure()
plt.plot(x, y)

plt.text(0.01, 0.23, r"$a = {0:s}$".format(as_si(a,2)), size=20)
plt.show()

【讨论】:

  • 这比我想出的方法更简单,更通用。但是,我不明白为什么需要 3 个嵌套大括号来格式化指数。我也不明白为什么它是“format(m=m, e=int(e))”而不是“format(m, int(e))”。
  • 您需要在 TeX 输出中使用一对大括号,并且通过在新样式的 Python 格式字符串中加倍({{}})获得单个文字大括号;命名(关键字)格式说明符是在format 函数中列出它们的替代方法。
猜你喜欢
  • 2023-03-10
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多