Search code examples
pythonpython-3.xmatplotlibbar-chartscientific-notation

Y axis label in scientific notation when multiple bar charts are plotted


I was trying to plot multiple bar charts as subplot but the y axis keeps on getting scientific notation values. The initial code I ran was:

from matplotlib import pyplot as plt
fig, axes = plt.subplots(7,3,figsize = (25, 40)) # axes is a numpy array of pyplot Axes
axes = iter(axes.ravel())  
cat_columns=['Source','Side','State','Timezone',
       'Amenity', 'Bump', 'Crossing', 'Give_Way',
       'Junction', 'No_Exit', 'Railway', 'Roundabout', 'Station', 'Stop',
       'Traffic_Calming', 'Traffic_Signal', 'Turning_Loop', 'Sunrise_Sunset',
       'Civil_Twilight', 'Nautical_Twilight', 'Astronomical_Twilight']
for col in cat_columns: 
    ax = df[col].value_counts().plot(kind='bar',label = col, ax=axes.__next__())  

And the output looks like this:

enter image description here

fig, axes = plt.subplots(7,3,figsize = (25, 40)) # axes is a numpy array of pyplot Axes
axes = iter(axes.ravel())  
cat_columns=['Source','Side','State','Timezone',
       'Amenity', 'Bump', 'Crossing', 'Give_Way',
       'Junction', 'No_Exit', 'Railway', 'Roundabout', 'Station', 'Stop',
       'Traffic_Calming', 'Traffic_Signal', 'Turning_Loop', 'Sunrise_Sunset',
       'Civil_Twilight', 'Nautical_Twilight', 'Astronomical_Twilight']
for col in cat_columns: 
    ax = df[col].value_counts().plot(kind='bar',label = col, ax=axes.__next__())
    ax.ticklabel_format(useOffset=False, style='plain') 

After using this line ax.ticklabel_format(useOffset=False, style='plain') I am getting an error like:

enter image description here

Please guide me on this error.


Solution

  • You can turn this off by creating a custom ScalarFormatter object and turning scientific notation off. For more details, see the matplotlib documentation pages on tick formatters and on ScalarFormatter.

    # additional import statement at the top
    from matplotlib import pyplot as plt
    from matplotlib import ticker
    
    # additional code for every axis
    formatter = ticker.ScalarFormatter()
    formatter.set_scientific(False)
    ax.yaxis.set_major_formatter(formatter)