gpt4 book ai didi

matplotlib - pyplot 中默认字体中每个刻度的科学记数法

转载 作者:行者123 更新时间:2023-12-03 16:33:28 26 4
gpt4 key购买 nike

所以我想要的是让我的 pyplot 以科学记数法记号。所以每个刻度看起来像 1x10^6 而不是 1,然后是轴上的 10^6。到目前为止,我能够做到这一点的唯一方法是手动将每个刻度标签设置为 r'$1\times10^6$',但这会将它放在数学表达式字体中,如果我尝试传递 fontdict,set_yticklabels 将不会听.

我将如何做到这一点?

最佳答案

我不确定我是否正确理解你的问题,但你想要这样的东西吗?

import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.logspace(1,10,10),np.logspace(1,5,10))
ax = plt.gca()
ax.get_xaxis().set_major_formatter(plt.LogFormatter(10, labelOnlyBase=False))
ax.get_yaxis().set_major_formatter(plt.LogFormatter(10, labelOnlyBase=False))

这使
enter image description here

更新:

上面显示的方法仅适用于数据范围足够大的情况。如果需要较小范围的科学记数法,可以将自定义格式化程序用作

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

def MyFormatter(x,lim):
if x == 0:
return 0
return '{0:.2f}e{1:.2f}'.format(np.sign(x)*10**(-np.floor(np.log10(abs(x)))+np.log10(abs(x))),np.floor(np.log10(abs(x))))
#The first argument of the format gives the first significant digits of the number with the sign preserved and brought to a range between [1-10), The next argument gives the numbers integer exponent of 10
#Both the first and second arguments are formatted to display only 2 decimal places due to the lack of space.

majorFormatter = FuncFormatter(MyFormatter)

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

fig, ax = plt.subplots()
plt.plot(t,s)

ax.xaxis.set_major_formatter(majorFormatter)

这给出了一个像
enter image description here

关于matplotlib - pyplot 中默认字体中每个刻度的科学记数法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20127388/

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