【问题标题】:How to turn on scientific notation in matplotilb bar chart?matplotlib条形图中如何开启科学计数法?
【发布时间】:2019-11-21 07:01:46
【问题描述】:

我试图在这个图中打开科学记数法,这样 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()

这是对应的情节:

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

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

ax.ticklabel_format(style='sci')

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

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

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

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

【问题讨论】:

    标签: python pandas matplotlib scientific-notation


    【解决方案1】:

    你可以在plt.show()前面加上这3行:

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

    还要检查这个link 以获得set_powerlimits()

    【讨论】:

      【解决方案2】:

      您需要使用scilimits 参数来设置应使用偏移量的限制。

      ax.ticklabel_format(style='sci', axis='y', useOffset=True, scilimits=(0,0))
      

      【讨论】:

        猜你喜欢
        • 2021-11-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-16
        • 2018-03-25
        • 2019-06-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多