如何使用十种格式的功能进行注释?

时间:2013-08-19 10:45:07

标签: matplotlib number-formatting

我希望注释中的数字类似于{x} \ cdot10 ^ {y},而不是现在的数字:{x} E + {y}。是否有适合的字符串格式化程序?

对我来说最理想的解决方案是使用格式字符串,例如'%。2e',但可以自动转换为十位表示法。

2 个答案:

答案 0 :(得分:10)

您可以定义自己的字符串格式化程序,以便与LaTeX或Mathtext一起使用。 在下面定义的函数sci_notation()中,您可以指定有效小数位数以及要打印的小数位数(默认为有效小数位数)。也可以明确指定应该使用哪个指数。

from math import floor, log10

# Use LaTeX as text renderer to get text in true LaTeX
# If the two following lines are left out, Mathtext will be used
import matplotlib as mpl
mpl.rc('text', usetex=True)

import matplotlib.pyplot as plt

# Define function for string formatting of scientific notation
def sci_notation(num, decimal_digits=1, precision=None, exponent=None):
    """
    Returns a string representation of the scientific
    notation of the given number formatted for use with
    LaTeX or Mathtext, with specified number of significant
    decimal digits and precision (number of decimal digits
    to show). The exponent to be used can also be specified
    explicitly.
    """
    if not exponent:
        exponent = int(floor(log10(abs(num))))
    coeff = round(num / float(10**exponent), decimal_digits)
    if not precision:
        precision = decimal_digits

    return r"${0:.{2}f}\cdot10^{{{1:d}}}$".format(coeff, exponent, precision)

SciNum = -3.456342e-12

# Annotation with exponent notation using `e` as separator
plt.annotate(SciNum, (0.5,0.5), ha='center', fontsize=20)

# Annotation with scientific notation using `\cdot 10` as separator
plt.annotate(sci_notation(SciNum,1), (0.5,0.4), ha='center', fontsize=20)

# Annotation with scientific notation using `\cdot 10` as separator
# with 1 significant decimal digit and 2 decimal digits shown as well
# as a given exponent.
plt.annotate(sci_notation(SciNum,1,2,exponent=-14), (0.5,0.3), ha='center', fontsize=20)

plt.title('Scientific notation', fontsize=14)

plt.show()

enter image description here

答案 1 :(得分:0)

def round_to_n(x, n):
    " Round x to n significant figures "
    return round(x, -int(py.floor(py.sign(x) * py.log10(abs(x)))) + n)

def str_fmt(x, n=2):
    " Format x into nice Latex rounding to n"
    power = int(py.log10(Round_To_n(x, 0)))
    f_SF = Round_To_n(x, n) * pow(10, -power)
    return r"${}\cdot 10^{}$".format(f_SF, power)

>>> x = 1203801.30201
>>> str_fmt(x)
$1.2\\cdot 10^6$

如何对此进行参数化存在许多变化,例如,您可以指定指数(y)而不是自动生成它,但原理保持不变。