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)/2 to find the center of each patch

  • Alternatively, calculate bin centers using (bins[:-1] + bins[1:]) / 2

  • The xticks() method takes positions and labels as arguments

  • You 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.

Updated on: 2026-03-25T21:09:19+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements