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
How to remove relative shift in Matplotlib axis?
When plotting data with large numerical values in Matplotlib, the axis labels often display with a relative shift (offset) to make them more readable. Sometimes you need to show the full values without this offset.
Understanding Relative Shift
By default, Matplotlib adds an offset to axis labels when values are large. For example, instead of showing 1000, 1001, 1002, it might show 0, 1, 2 with "+1000" at the corner.
Removing the Offset
To remove the relative shift, access the axis formatter and disable the offset using set_useOffset(False) ?
from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Plot data with large values plt.plot([1000, 1001, 1002], [1, 2, 3]) # Remove relative shift on x-axis plt.gca().get_xaxis().get_major_formatter().set_useOffset(False) plt.show()
Complete Example
Here's a more comprehensive example showing the difference ?
import matplotlib.pyplot as plt
# Create subplot to compare
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
# Data with large values
x_data = [10, 101, 1001]
y_data = [1, 2, 3]
# Plot with default offset
ax1.plot(x_data, y_data, 'b-o')
ax1.set_title('With Offset (Default)')
# Plot without offset
ax2.plot(x_data, y_data, 'r-o')
ax2.get_xaxis().get_major_formatter().set_useOffset(False)
ax2.set_title('Without Offset')
plt.tight_layout()
plt.show()
Alternative Method
You can also disable offset globally for all plots ?
import matplotlib.pyplot as plt from matplotlib.ticker import ScalarFormatter # Set global formatter plt.rcParams['axes.formatter.useoffset'] = False # Or use ScalarFormatter directly formatter = ScalarFormatter(useOffset=False) plt.gca().xaxis.set_major_formatter(formatter)
Key Methods
gca()− Gets the current axisget_xaxis()− Returns the X-axis instanceget_major_formatter()− Gets the formatter for major ticksset_useOffset(False)− Disables the offset display
Conclusion
Use set_useOffset(False) on the axis formatter to display full numerical values without relative shifts. This is particularly useful when working with large numbers or when precise values need to be visible.
