简体   繁体   中英

How to turn on scientific notation in matplotilb bar chart?

I am trying to turn on scientific notation in this plot so that the numbers on the y-axis don't take up so much space.

Currently my code is:

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

And this is the corresponding plot:

在此处输入图像描述

Basically my question is the opposite of this one .

I had the same error message and resolved it by changing

ax.ticklabel_format(style='sci')

to

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

I tried using FuncFormatter to produce customized scientific notation, but I didn't like the result because each tick on the axis was labeled with the exponent

在此处输入图像描述

rather than the exponent/offset simply being marked at the top of the axis like in the following image (from the internet)

在此处输入图像描述

How can I get my plot to use the default scientific notation from matplotlib ?

You can add these 3 lines before plt.show() :

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

Check also this link for set_powerlimits() 在此处输入图像描述

You need to use the scilimits argument to set the limits over which the offset should be used.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM