是否可以将x轴刻度线与matplotlib直方图中的相应条对齐? [英] Is it possible to align x-axis ticks with corresponding bars in a matplotlib histogram?

查看:114
本文介绍了是否可以将x轴刻度线与matplotlib直方图中的相应条对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在绘制时间序列日期时,我正在尝试绘制每小时的数据点数:

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)])

x轴刻度线已正确显示并标记,但条形图本身在刻度线上方未正确对齐.条形图更多地绘制在中心,将其设置在左侧刻度线的右侧,而将右侧刻度线的左侧设置.

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.

align ='mid'选项允许我们将xticks移到'left'/'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.

是否可以将条形图设置在直方图中相应刻度的正上方?

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

为了不跳过细节,这里设置了一些参数,以便通过imgur的黑色背景获得更好的可见性

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

推荐答案

当您放入 bins = 24 时,您每小时不会得到一个垃圾箱.假设您的小时数是从0到23的整数, bins = 24 将创建24个bin,将0.0到23.0的范围划分为24个相等的部分.因此,区域将是 0-0.958 0.958-1.917 1.917-2.75 ,... 22.042-23 .如果值不包含 0 23 ,则会发生奇怪的事情,因为将在遇到的最低值和最高值之间创建范围.

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.

由于数据是离散的,因此强烈建议显式设置bin边缘.例如数字 -0.5-0.5 0.5-1.5 ,....

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

这篇关于是否可以将x轴刻度线与matplotlib直方图中的相应条对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆