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 center labels in a Matplotlib histogram plot?
To place the labels at the center in a histogram plot, we can calculate the mid-point of each patch and place the ticklabels accordingly using xticks() method. This technique provides better visual alignment between the labels and their corresponding histogram bars.
Steps
Set the figure size and adjust the padding between and around the subplots.
Create a random standard sample data, x.
Initialize a variable for number of bins.
Use
hist()method to make a histogram plot.Calculate the list of ticks at the center of each patch.
Make a list of tick labels.
Use
xticks()method to place xticks and labels.To display the figure, use
show()method.
Example
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create random sample data x = np.random.randn(1000) n_bins = 10 # Create histogram and get patches n, bins, patches = plt.hist(x, bins=n_bins, edgecolor='black') # Calculate tick positions at center of each patch ticks = [(patch._x0 + patch._x1)/2 for patch in patches] ticklabels = [i for i in range(n_bins)] # Set centered tick labels plt.xticks(ticks, ticklabels) plt.show()
The output of the above code is ?
[Displays a histogram with labels centered under each bar]
Alternative Method Using Bin Centers
You can also calculate the bin centers directly from the bins array returned by hist() ?
import numpy as np
from matplotlib import pyplot as plt
# Create sample data
x = np.random.randn(1000)
n_bins = 10
# Create histogram
n, bins, patches = plt.hist(x, bins=n_bins, edgecolor='black')
# Calculate bin centers from bins array
bin_centers = (bins[:-1] + bins[1:]) / 2
ticklabels = ['Bin ' + str(i) for i in range(n_bins)]
# Set centered tick labels
plt.xticks(bin_centers, ticklabels, rotation=45)
plt.title('Histogram with Centered Labels')
plt.show()
The output shows a histogram with descriptive labels centered under each bin ?
[Displays a histogram with "Bin 0", "Bin 1", etc. labels centered under each bar]
Key Points
Use
(patch._x0 + patch._x1)/2to find the center of each patchAlternatively, calculate bin centers using
(bins[:-1] + bins[1:]) / 2The
xticks()method takes positions and labels as argumentsYou can customize labels with descriptive text or numbers
Conclusion
Centering labels in matplotlib histograms improves readability by aligning labels with their corresponding bars. Use patch coordinates or bin centers to calculate precise positioning for optimal visual presentation.
