Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

enter image description here

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. Ideally, I'd like to show my data in (mln).

like image 464
aviss Avatar asked Oct 13 '17 18:10

aviss


People also ask

How do I stop matplotlib from scientific notation?

If you want to disable both the offset and scientific notaion, you'd use ax. ticklabel_format(useOffset=False, style='plain') .

How do I get rid of scientific notation in Python?

Use a string literal to suppress scientific notation Use the string literal syntax f"{num:. nf}" to represent num in decimal format with n places following the decimal point.

How do you do scientific notation in Python?

Python has a defined syntax for representing a scientific notation. So, let us take a number of 0.000001234 then to represent it in a scientific form we write it as 1.234 X 10^-6. For writing it in python's scientific form we write it as 1.234E-6. Here the letter E is the exponent symbol.


1 Answers

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), ',')))

enter image description here

And then I can use int(x)/ to convert to million or thousand as I wish:

enter image description here

like image 69
aviss Avatar answered Sep 30 '22 12:09

aviss