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 force Matplotlib to show the values on X-axis as integers?
By default, Matplotlib may display decimal values on the X-axis when plotting data. To force the X-axis to show only integer values, you can use plt.xticks() with a range of integers or set a custom tick locator.
Method 1: Using plt.xticks() with range()
Create a range of integers based on your data's minimum and maximum values ?
import math
import matplotlib.pyplot as plt
# Sample data
x = [1.0, 1.75, 2.90, 3.15, 4.50, 5.50]
y = [0.17, 1.17, 2.98, 3.15, 4.11, 5.151]
plt.figure(figsize=(8, 5))
plt.plot(x, y, marker='o')
# Force integer ticks on X-axis
integer_ticks = range(math.floor(min(x)), math.ceil(max(x)) + 1)
plt.xticks(integer_ticks)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Integer Values Only on X-axis")
plt.grid(True, alpha=0.3)
plt.show()
# Displays a plot with X-axis showing only integers: 1, 2, 3, 4, 5, 6
Method 2: Using MultipleLocator
For more control, use MultipleLocator from matplotlib.ticker ?
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
# Sample data
x = [0.5, 1.2, 2.8, 3.9, 5.1, 6.7]
y = [1, 4, 2, 8, 3, 6]
plt.figure(figsize=(8, 5))
plt.plot(x, y, 'b-o', linewidth=2, markersize=6)
# Set major ticks to appear at integer intervals
plt.gca().xaxis.set_major_locator(MultipleLocator(1))
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Using MultipleLocator for Integer Ticks")
plt.grid(True, alpha=0.3)
plt.show()
# Displays a plot with X-axis ticks at every integer value
Method 3: Custom Integer Range
Manually specify the exact integer values you want to display ?
import matplotlib.pyplot as plt
# Sample data
categories = [1.1, 2.3, 3.7, 4.2, 5.8]
values = [10, 25, 15, 30, 20]
plt.figure(figsize=(8, 5))
plt.bar(categories, values, alpha=0.7, color='skyblue')
# Set custom integer ticks
custom_ticks = [1, 2, 3, 4, 5, 6]
plt.xticks(custom_ticks)
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Chart with Integer X-axis")
plt.show()
# Displays a bar chart with X-axis showing integers 1, 2, 3, 4, 5, 6
Comparison
| Method | Best For | Flexibility |
|---|---|---|
plt.xticks(range()) |
Simple plots with continuous data | Low |
MultipleLocator |
Complex plots, subplots | High |
| Custom ticks list | Specific integer values | Medium |
Conclusion
Use plt.xticks(range()) for simple cases or MultipleLocator(1) for more advanced control. Both methods ensure your X-axis displays clean integer values instead of decimals.
Advertisements
