python - 如何在matplotlib条形图中打开科学记数法?

标签 python pandas matplotlib scientific-notation

我试图在该图中打开科学记数法,以便 y 轴上的数字不会占用太多空间。

目前我的代码是:

import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd

mpl.rcParams.update({'font.size':15})
mpl.rcParams.update({'legend.columnspacing':0.5})

energy_cm = 1550835.86856494
energy_fm = 1456129.29966378
energy_cm_trad = 1393026.50949191
energy_fm_trad = 1314814.95236864
energy_cm_hw = 1200000
energy_fm_hw = 1100000

data_energy = { 'Algorithm' : ['Algorithm 1', 'Algorithm 2'],
       'SW' : [energy_cm, energy_fm],
       'HW' : [energy_cm_hw, energy_fm_hw],
       'Trad' : [energy_cm_trad, energy_fm_trad]
    }

df_energy = pd.DataFrame(data_energy)

width = 0.7
fig = plt.figure(figsize=(8, 8))
ax = plt.axes()
df_energy[['Algorithm', 'SW', 'Trad', 'HW']].set_index('Algorithm').plot(kind='bar', legend=True, width=width, rot=0, ax=ax, color=('sandybrown','rosybrown', 'goldenrod','indianred','tomato','r'))

ax.set_ylabel('Energy in nJ')

ax.ticklabel_format(style='sci', axis='y')
# ax.yaxis.set_major_formatter(scientific_formatter)
# ax.ticklabel_format(useOffset=True, axis='y')

fig.tight_layout()
plt.show()

这是相应的情节:

enter image description here

基本上我的问题是 opposite of this one

我有同样的错误消息并通过更改解决了它

ax.ticklabel_format(style='sci')

ax.ticklabel_format(style='sci', axis='y')

我尝试使用 FuncFormatter 生成自定义的科学记数法,但我不喜欢这个结果,因为轴上的每个刻度都标有指数

enter image description here

而不是简单地在轴的顶部标记指数/偏移量,如下图所示(来自互联网)

enter image description here

如何让我的绘图使用 matplotlib 中的默认科学记数法?

最佳答案

您可以在plt.show()之前添加这3行:

mf = mpl.ticker.ScalarFormatter(useMathText=True)
mf.set_powerlimits((-2,2))
plt.gca().yaxis.set_major_formatter(mf)

另请检查此 link对于set_powerlimits() enter image description here

关于python - 如何在matplotlib条形图中打开科学记数法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58969040/

相关文章:

python - 从 DateTime Pandas 系列中提取小时数

python - 如何在Python中使用matlibplot在子图上绘制矩形?

python - 为什么 matplotlib spins 有 "set_label"和 "get_label"方法?

python - 优化 python/pypy 中的蛮力过程以查找独生子女号码

Python 2.7 - 导入错误 : No module named Image

python - 使用字符串搜索列表

python - 使用 Qt Designer 表单和 PyQt5 在 QWidget 中绘制 matplotlib 图

python - Julia 符号和数字性能对比 Python

python - Pandas - 使用 itertuples 创建列

python - Panda Python - 将一列除以 100(然后四舍五入为 2.dp)