[英]How to convert float notation to power of 10 scientific notation in Python?
在Python
,我将由0.000001,0.00001,0.0001,....,1.0
给出的值存储在my_Array
( np.array
)中。 对于这些值中的每一个,我都需要在图中标出一条曲线并将其存储在图例中,即val = 10e-6
而不是val = 0.000001
。 如果我使用第二个版本,则会自动存储(第i
个值):
matplolib.pyplot.plot(...., label = 'val = ' + str(my_Array[i]))
是否有将浮点表示法转换为10表示法科学能力的函数?
您可以结合使用ScalarFormatter
和FuncFormatter
将值格式化为mathtext。 即代替0.01或1e-2它看起来像 。
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
vals = [0.000001,0.00001,0.0001,0.01,1.0]
f = mticker.ScalarFormatter(useOffset=False, useMathText=True)
g = lambda x,pos : "${}$".format(f._formatSciNotation('%1.10e' % x))
fmt = mticker.FuncFormatter(g)
fig, ax = plt.subplots()
for i,val in enumerate(vals):
ax.plot([0,1],[i,i], label="val = {}".format(fmt(val)))
ax.legend()
plt.show()
这与“ 我可以在matplotlib图的轴上显示小数位和科学计数法”中的概念基本相同。 ,而不是轴,而是图例。
您只需要在'%.2E%'和所需数字之间进行取整即可。
'%.2E' % Decimal('40800000000.00000000000000')
# returns '4.08E+10'
'%.2E%'舍入到小数点后第二位。 要舍入为第一个,请使用'%.1E%'。
--
要实现您想要的,只需:
x = 0.0001
y = '%.2E' % x
print (y)
# prints 1.00E-04
(在琼斯·哈珀的笔尖之后编辑)
从理论上讲,以下内容无需调用私有函数即可工作。 但是,在3.11版中至少有一些问题,至少是这样的,以至于实际上在ScalarFormatter内都没有检查功率限制。
import matplotlib.ticker as mticker
f = mticker.ScalarFormatter(useMathText=True)
f.set_powerlimits((-3,3))
"${}$".format(f.format_data(0.0001))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.