tem*_*eff 19 python matplotlib significant-digits python-2.7 axis-labels
我正在使用python 2.7在pyqt程序中使用matplotlib绘制一些大数字.我的y轴范围从1e + 18到3e + 18(通常).我想看到每个刻度线以科学记数法显示值,并带有2位小数.例如2.35e + 18而不仅仅是2e + 18,因为2e + 18和3e + 18之间的值仍然只读取2e + 18的几个标记.这是一个问题的例子.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 300, 20)
y = np.linspace(0,300, 20)
y = y*1e16
ax.plot(x,y)
ax.get_xaxis().set_major_formatter(plt.LogFormatter(10, labelOnlyBase=False))
ax.get_yaxis().set_major_formatter(plt.LogFormatter(10, labelOnlyBase=False))
plt.show()
Run Code Online (Sandbox Code Playgroud)
Ffi*_*ydd 42
如果你使用的matplotlib.ticker.FormatStrFormatter是相反的,那么这很容易做到LogFormatter.以下代码将使用以下格式标记所有内容'%.2e':
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 300, 20)
y = np.linspace(0,300, 20)
y = y*1e16
ax.plot(x,y)
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
plt.show()
Run Code Online (Sandbox Code Playgroud)

为了获得科学表示法格式正确的标签,可以使用ScalarFormatter使用MathText(Latex)的a的格式化功能,并将其应用于标签。
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mticker
fig, ax = plt.subplots()
x = np.linspace(0, 300, 20)
y = np.linspace(0,300, 20)
y = y*1e16
ax.plot(x,y)
f = mticker.ScalarFormatter(useOffset=False, useMathText=True)
g = lambda x,pos : "${}$".format(f._formatSciNotation('%1.10e' % x))
plt.gca().yaxis.set_major_formatter(mticker.FuncFormatter(g))
plt.show()
Run Code Online (Sandbox Code Playgroud)
尽管这在很多情况下可能很有用,但实际上并不能满足问题的要求。要使所有标签上的位数均相等,可以使用更自定义的版本。
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mticker
fig, ax = plt.subplots()
x = np.linspace(0, 300, 20)
y = np.linspace(0,300, 20)
y = y*1e16
ax.plot(x,y)
class MathTextSciFormatter(mticker.Formatter):
def __init__(self, fmt="%1.2e"):
self.fmt = fmt
def __call__(self, x, pos=None):
s = self.fmt % x
decimal_point = '.'
positive_sign = '+'
tup = s.split('e')
significand = tup[0].rstrip(decimal_point)
sign = tup[1][0].replace(positive_sign, '')
exponent = tup[1][1:].lstrip('0')
if exponent:
exponent = '10^{%s%s}' % (sign, exponent)
if significand and exponent:
s = r'%s{\times}%s' % (significand, exponent)
else:
s = r'%s%s' % (significand, exponent)
return "${}$".format(s)
# Format with 2 decimal places
plt.gca().yaxis.set_major_formatter(MathTextSciFormatter("%1.2e"))
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45100 次 |
| 最近记录: |