Can I turn off scientific notation in matplotlib bar chart?
Asked Answered
E

2

7

I have a bar chart that looks like how I want it to look, except for the scientific notation on the y-axes.

Some other solutions included using

ax.yaxis.set_major_formatter(tick)

which didn't work. Also, I tried checking whether this was an offset-problem, but it should have shown a '+' sign, which it doesn't in this case.

Whenever I use:

plt.ticklabel_format(style='plain')

I get an error message saying:

Traceback (most recent call last):
  File "C:\Python\lib\site-packages\matplotlib\axes\_base.py", line 2831, in ticklabel_format
    self.xaxis.major.formatter.set_scientific(sb)
AttributeError: 'FixedFormatter' object has no attribute 'set_scientific'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Python/Projects/Kaggle 1.py", line 13, in <module>
    plt.ticklabel_format(style='plain')
  File "C:\Python\lib\site-packages\matplotlib\pyplot.py", line 2982, in ticklabel_format
    useMathText=useMathText)
  File "C:\Python\lib\site-packages\matplotlib\axes\_base.py", line 2856, in ticklabel_format
    "This method only works with the ScalarFormatter.")
AttributeError: This method only works with the ScalarFormatter.

I've looked into this ScalarFormatter, but I couldn't get any wiser as to why it doesn;t work. I've tried to explicitly include it in the code, but it doesn't work.

The code I use is:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv("100 Sales Records.csv")
df_new = df.groupby(['Region']).sum().sort_values("Total Profit", ascending=False)
regions = ('Sub-Saharan Africa', 'Europe', 'Asia', 'Middle East and North Africa', 'Australia and Oceania', 'Central America and the Caribbean', 'North America')
profit = df_new['Total Profit']
y_pos = np.arange(len(profit))

plt.bar(y_pos, profit)
plt.xticks(y_pos, regions)
plt.ticklabel_format(style='plain')
plt.title('Sum of Sales')

plt.show()

The chart currently looks like this:

enter image description here

Expectation answered 13/1, 2019 at 2:14 Comment(2)
By the way, you should write a Minimal, Complete, and Verifiable example or MCVE. Your example can't be pasted and run on other people's computers because it accesses several unrelated libraries and data files. You should write a short script that exhibits the same problem using a small amount of data within your script.Adila
See this comment. When you set the format you should only set it to the y axis, not both, plt.ticklabel_format(axis="y", style='plain')Carl
L
5

You can use FuncFormatter of the matplotlib.ticker to update the ticks as you wish on your current plot. In my example below, the ticks are updated using a custom scientific_formatter, that I defined to update the ticks in scientific notation with 2 precision digits - %2E.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

profit = pd.Series(np.random.randint(1e2, size=5))
ax = profit.plot(kind="bar")

def scientific(x, pos):
    # x:  tick value - ie. what you currently see in yticks
    # pos: a position - ie. the index of the tick (from 0 to 9 in this example)
    return '%.2E' % x

scientific_formatter = FuncFormatter(scientific)
ax.yaxis.set_major_formatter(scientific_formatter)
Laroche answered 13/1, 2019 at 3:19 Comment(1)
Good question. The ax variable is of type matplotlib.axes._subplots.AxesSubplot, so not related anymore to the pandas libraryLaroche
A
5

@ImportanceOfBeingErnest is correct in the comment. The error is because plt.ticklabel_format(style='plain') by default set both axes to be plain whereas your xticks are customed and cannot be plain.

Use plt.ticklabel_format(axis="y", style='plain') to set y-axis alone.

Adler answered 24/5, 2021 at 21:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.