Matplotlib pyplot中默认字体中每个勾号的科学符号

Matplotlib pyplot中默认字体中每个勾号的科学符号,matplotlib,Matplotlib,所以我想让我的pyplot用科学记数法。因此,每个刻度看起来像1x10^6,而不是1,然后是轴上的10^6。到目前为止,我唯一能够做到这一点的方法是手动将每个ticklebel设置为r'$1\times10^6$',但这会将其置于数学表达式字体中,并且如果我试图传递fontdict,set_yticklebels将不会侦听 我怎样才能做到这一点呢?我不确定我是否正确理解了你的问题,但你想要这样的东西吗 导入matplotlib.pyplot作为plt 将numpy作为np导入 plt.绘图(np

所以我想让我的pyplot用科学记数法。因此,每个刻度看起来像1x10^6,而不是1,然后是轴上的10^6。到目前为止,我唯一能够做到这一点的方法是手动将每个ticklebel设置为r'$1\times10^6$',但这会将其置于数学表达式字体中,并且如果我试图传递fontdict,set_yticklebels将不会侦听


我怎样才能做到这一点呢?

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

导入matplotlib.pyplot作为plt
将numpy作为np导入
plt.绘图(np.对数空间(1,10,10),np.对数空间(1,5,10))
ax=plt.gca()
ax.get_xaxis().set_major_格式化程序(plt.LogFormatter(10,labelOnlyBase=False))
ax.get\u yaxis().set\u major\u格式化程序(plt.LogFormatter(10,labelOnlyBase=False))
这就给了

更新: 上述方法仅在数据范围足够大的情况下有效。如果需要较小范围的科学符号,可以使用自定义格式化程序作为

将numpy导入为np
将matplotlib.pyplot作为plt导入
从matplotlib.ticker导入FuncFormatter
def MyFormatter(x,lim):
如果x==0:
返回0
返回'{0:.2f}e{1:.2f}'。格式(np.sign(x)*10**(-np.floor(np.log10(abs(x)))+np.log10(abs(x))),np.floor(np.log10(abs(x)))
#格式的第一个参数给出保留符号的数字的第一个有效数字,并将其带到[1-10]之间的范围,下一个参数给出数字的整数指数10
#由于缺少空间,第一个和第二个参数的格式都设置为仅显示2位小数。
majorFormatter=FuncFormatter(MyFormatter)
t=np.arange(0.0100.0,0.1)
s=np.sin(0.1*np.pi*t)*np.exp(-t*0.01)
图,ax=plt.子批次()
平面图(t,s)
ax.xaxis.set_major_格式化程序(majorFormatter)
这会产生一个类似

对于负值(因为log(x)为负x返回Nan),更新后的答案对我不起作用

此外,我认为以下内容要简单得多:

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

def MyFormatter(x,lim):
  if x == 0:
      return 0
  else:
    x = str(x).split("e")
    return x[0] + r"$\times 10^{" + x[1] + r"}$"
  # end if/else
# end def
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)

基于Jakob的答案,但使用python内置的科学符号字符串格式

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

def sci_format(x,lim):
    return '{:.1e}'.format(x)

major_formatter = FuncFormatter(sci_format)

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(major_formatter)

可能的重复不是这些主题的重复。我想要科学符号,我没有偏移量,它只是将数量级与每个刻度标签分开。我不希望它这样做。是的,这就是我想要的,但我不知道如何使用ScalarFormatter而不是LogFormatter来实现这一点。科学符号是创建的使用LogFormatter,所以我不明白你的意思。