Skip to content Skip to sidebar Skip to footer

Is It Possible To Align X-axis Ticks With Corresponding Bars In A Matplotlib Histogram?

While plotting time-series date, i'm trying to plot the number of data points per hour: fig, ax = plt.subplots() ax.hist(x = df.index.hour, bins = 24, # draw one ba

Solution 1:

When you put bins=24, you don't get one bin per hour. Supposing your hours are integers from 0 up to 23, bins=24 will create 24 bins, dividing the range from 0.0 to 23.0 into 24 equal parts. So, the regions will be 0-0.958, 0.958-1.917, 1.917-2.75, ... 22.042-23. Weirder things will happen in case the values don't contain 0 or 23 as the ranges will be created between the lowest and highest value encountered.

As your data is discrete, it is highly recommended to explicitly set the bin edges. For example number -0.5 - 0.5, 0.5 - 1.5, ... .

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.hist(x=np.random.randint(0, 24, 500),
        bins=np.arange(-0.5, 24),  # one bin per hour
        rwidth=0.6,  # adding a bit of space between each bar
        )
ax.set_xticks(ticks=np.arange(0, 24)) # the default tick labels will be these same numbers
ax.margins(x=0.02) # less padding left and right
plt.show()

example plot

Post a Comment for "Is It Possible To Align X-axis Ticks With Corresponding Bars In A Matplotlib Histogram?"