所以我想要的是让我的pyplot以科学记数法表示。所以每个刻度看起来像1x10 ^ 6而不是1,然后是轴上的10 ^ 6。到目前为止,我能够做到这一点的唯一方法是手动将每个ticklabel设置为r'$ 1 \ times10 ^ 6 $',但这会将其置于数学表达式字体中,如果我尝试传递fontdict,则set_yticklabels不会听
我将如何做到这一点?
答案 0 :(得分:5)
我不确定我是否理解你的问题,但是你想要这样的东西吗?
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))
给出了
上面显示的方法仅在数据范围足够大时才有效。如果想要较小范围的科学记数法,可以使用自定义格式化程序
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)
这给出了一个类似于的情节
答案 1 :(得分:0)
(更新的)答案对我来说不适用于负值(因为log(x)返回Nan为负x)。
另外,我认为以下内容更为简单:
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)
答案 2 :(得分:0)
建立在雅各布的答案上,但使用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)