简体   繁体   English

如何在matplotlib中控制科学计数法?

[英]How to control scientific notation in matplotlib?

This is my data frame I'm trying to plot: 这是我要绘制的数据框:

my_dic = {'stats': {'apr': 23083904,
                       'may': 16786816,
                       'june': 26197936,
                     }}
my_df = pd.DataFrame(my_dic)
my_df.head()

This is how I plot it: 这是我的绘图方式:

ax = my_df['stats'].plot(kind='bar',  legend=False)
ax.set_xlabel("Month", fontsize=12)
ax.set_ylabel("Stats", fontsize=12)
ax.ticklabel_format(useOffset=False) #AttributeError: This method only works with the ScalarFormatter.
plt.show()

The plot: 剧情:

在此处输入图片说明

I'd like to control the scientific notation. 我想控制科学计数法。 I tried to suppress it by this line as was suggested in other questions plt.ticklabel_format(useOffset=False) but I get this error back - AttributeError: This method only works with the ScalarFormatter . 我试图按照其他问题plt.ticklabel_format(useOffset=False)建议通过此行来抑制它,但是我得到了此错误AttributeError: This method only works with the ScalarFormatter Ideally, I'd like to show my data in (mln). 理想情况下,我想以(mln)显示数据。

Since you already using pandas 由于您已经在使用pandas

import matplotlib.pyplot as plt
my_df.plot(kind='bar')
plt.ticklabel_format(style='plain', axis='y')

在此处输入图片说明

Adding this line helps to get numbers in a plain format but with ',' which looks much nicer: 添加此行有助于获取纯格式的数字,但带有','看起来更好:

ax.get_yaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

在此处输入图片说明

And then I can use int(x)/ to convert to million or thousand as I wish: 然后,我可以根据需要使用int(x)/转换为百万或千:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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