简体   繁体   English

如何在Python中将浮点表示法转换为10种科学表示法的功效?

[英]How to convert float notation to power of 10 scientific notation in Python?

In Python , I have values given by 0.000001,0.00001,0.0001,....,1.0 stored in my_Array ( np.array ). Python ,我将由0.000001,0.00001,0.0001,....,1.0给出的值存储在my_Arraynp.array )中。 For each of these values I need to label a curve in a plot and store it in the legend as val = 10e-6 instead of val = 0.000001 . 对于这些值中的每一个,我都需要在图中标出一条曲线并将其存储在图例中,即val = 10e-6而不是val = 0.000001 The second version is automatically stored if I use (for the i 'th value): 如果我使用第二个版本,则会自动存储(第i个值):

matplolib.pyplot.plot(...., label = 'val = ' + str(my_Array[i]))

Is there a function converting the float notation to the scientific power of 10 notation? 是否有将浮点表示法转换为10表示法科学能力的函数?

You may use a combination of a ScalarFormatter and a FuncFormatter to format your values as mathtext. 您可以结合使用ScalarFormatterFuncFormatter将值格式化为mathtext。 Ie instead of 0.01 or 1e-2 it would look like 即代替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()

在此处输入图片说明

This is essentially the same concept as in Can I show decimal places and scientific notation on the axis of a matplotlib plot? 这与“ 我可以在matplotlib图的轴上显示小数位和科学计数法”中的概念基本相同 , just not for the axes, but the legend. ,而不是轴,而是图例。

You can just get the round between '%.2E%' and the desired number. 您只需要在'%.2E%'和所需数字之间进行取整即可。

'%.2E' % Decimal('40800000000.00000000000000')

# returns '4.08E+10'

as seen on Display a decimal in scientific notation 以科学计数形式显示小数

The '%.2E%' rounds to the 2nd decimal point. '%.2E%'舍入到小数点后第二位。 To round to just the first one, use '%.1E%'. 要舍入为第一个,请使用'%.1E%'。

- --

To achieve what you want, just: 要实现您想要的,只需:

x = 0.0001
y = '%.2E' % x

print (y)

# prints 1.00E-04

(EDITED after jonrsharpe's tip) (在琼斯·哈珀的笔尖之后编辑)

In theory the below should work without the need to call private functions. 从理论上讲,以下内容无需调用私有函数即可工作。 However, something is broken in version 3.11 at least such that no check to the power limits is actually done inside ScalarFormatter. 但是,在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM