Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to prevent numbers being changed to exponential form in Python Matplotlib?
When plotting large numbers in Matplotlib, the axis labels often switch to scientific notation (exponential form) automatically. You can prevent this by using the ticklabel_format() with style='plain' parameter.
Syntax
plt.ticklabel_format(style='plain')
The style='plain' parameter turns off scientific notation and displays numbers in their regular decimal format.
Example
Here's how to prevent exponential notation when plotting data ?
import matplotlib.pyplot as plt
# Plot data that would normally trigger scientific notation
plt.plot([1, 2, 3, 4, 5], [11000, 12000, 13000, 14000, 15000])
# Prevent scientific notation on y-axis
plt.ticklabel_format(style='plain')
plt.title('Numbers in Plain Format')
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.show()
Controlling Specific Axes
You can also control formatting for specific axes using the axis parameter ?
import matplotlib.pyplot as plt
# Create data with large numbers
x_values = [100000, 200000, 300000, 400000, 500000]
y_values = [0.001, 0.002, 0.003, 0.004, 0.005]
plt.plot(x_values, y_values)
# Apply plain format only to x-axis
plt.ticklabel_format(style='plain', axis='x')
plt.title('Plain Format on X-axis Only')
plt.xlabel('Large X Values')
plt.ylabel('Small Y Values (Scientific)')
plt.show()
Key Parameters
| Parameter | Options | Description |
|---|---|---|
style |
'plain', 'scientific' | Format style for tick labels |
axis |
'x', 'y', 'both' | Which axis to apply formatting |
useOffset |
True, False | Whether to use offset notation |
Alternative Method Using Formatter
You can also use FuncFormatter for more control over number formatting ?
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
def plain_formatter(x, pos):
return f'{int(x):,}'
# Create plot with large numbers
plt.plot([1, 2, 3, 4, 5], [1000000, 2000000, 3000000, 4000000, 5000000])
# Apply custom formatter to y-axis
plt.gca().yaxis.set_major_formatter(FuncFormatter(plain_formatter))
plt.title('Custom Number Formatting')
plt.xlabel('X Values')
plt.ylabel('Y Values (with commas)')
plt.show()
Conclusion
Use plt.ticklabel_format(style='plain') to prevent scientific notation in Matplotlib plots. For more control, use custom formatters with the FuncFormatter class.
Advertisements
