Is it possible to align x-axis ticks with corresponding bars in a matplotlib histogram?

北战南征 提交于 2021-02-05 07:51:33

问题


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 bar per hour 
        align = 'mid'      # this is where i need help
        rwidth = 0.6,      # adding a bit of space between each bar
        )

I want one bar per hour, each hour labeled, so we set:

ax.set_xticks(ticks = np.arange(0, 24))
ax.set_xticklabels(labels = [str(x) for x in np.arange(0, 24)])

The x-axis ticks are shown and labelled correctly, yet the bars themselves are not correctly aligned above the ticks. Bars are more drawn to the center, setting them right of the ticks on the left, while left of the ticks on the right.

The align = 'mid' option allows us, to shift the xticks to 'left' / 'right', yet neither of those is helping with the problem at hand.

missaligned barplot

Is there a way of setting the bars exactly above the corresponding ticks in a histogram?

To not skip details, here a few params set for better visibility via black background at imgur

fig.patch.set_facecolor('xkcd:mint green')
ax.set_xlabel('hour of the day')
ax.set_ylim(0, 800)
ax.grid()
plt.show()

回答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()



来源:https://stackoverflow.com/questions/65423518/is-it-possible-to-align-x-axis-ticks-with-corresponding-bars-in-a-matplotlib-his

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!