gpt4 book ai didi

matplotlib - 如何使用十种格式进行注释?

转载 作者:行者123 更新时间:2023-12-04 10:52:36 25 4
gpt4 key购买 nike

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

对我来说最理想的解决方案是使用格式字符串,如“%.2e”,但自动转换为十次幂。

最佳答案

您可以定义自己的字符串格式化程序以用于 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 exponent is None:
exponent = int(floor(log10(abs(num))))
coeff = round(num / float(10**exponent), decimal_digits)
if precision is None:
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

关于matplotlib - 如何使用十种格式进行注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18311909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com