在 Xaxis python 中使用科学记数法

问题描述

我正在尝试在 xaxis 上绘制具有一些非常小的值的数据集。我想对 Xaxis 上的所有数字使用科学记数法。所以我尝试了

plt.ticklabel_format(style='sci',axis='x',scilimits=(0,0))

我收到以下错误

xis.major.formatter.set_scientific(is_sci_style)
AttributeError: 'FuncFormatter' object has no attribute 'set_scientific'

有人能帮我吗,非常感谢。

我的情节:

enter image description here

解决方法

要应用科学记数法,您可以使用格式化程序功能。请参阅此帖子:Can I turn of scientific notation in matplotlib bar chart?。我在引用的参考文献中应用了与用户相同的逻辑,以获得以下简单示例,该示例是在两个轴上都带有科学记数法的正弦函数图。

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

x = np.linspace(0,100,1000)
y = np.sin(x)

def scientific(x,pos):
    # x:  tick value
    # pos: tick position
    return '%.2E' % x

# create figure
plt.figure()
# plot sine
plt.plot(x,y)
# get current axes 
ax = plt.gca()
# initialize formatter
scientific_formatter = FuncFormatter(scientific)
# apply formatter on x and y axes
ax.xaxis.set_major_formatter(scientific_formatter)
ax.yaxis.set_major_formatter(scientific_formatter)
# show plot
plt.show()