【问题标题】:Is it possible to align x-axis ticks with corresponding bars in a matplotlib histogram?是否可以将 x 轴刻度与 matplotlib 直方图中的相应条对齐?
【发布时间】:2021-05-05 01:13:54
【问题描述】:

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

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
        )

我想要每小时一根,每个小时都有标签,所以我们设置:

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

x 轴刻度已正确显示和标记,但条本身在刻度上方未正确对齐。条形图更靠近中心,将它们设置在左侧刻度线的右侧,而右侧刻度线的左侧。

align = 'mid' 选项允许我们将 xticks 转移到 'left' / 'right',但这些都无法解决手头的问题。

有没有办法将条形设置在直方图中相应刻度的正上方?

为了不跳过细节,这里设置了一些参数,以便通过 imgur 的黑色背景更好地查看

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

【问题讨论】:

  • 这有点令人困惑,因为直方图考虑的是 bin,而不是刻度。所以每个条基本上代表一个范围(这就是为什么条之间的空间可能会产生误导)。您是否考虑过切换到普通条形图,您可以将每个条形图放置在特定位置?

标签: python matplotlib histogram


【解决方案1】:

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

由于您的数据是离散的,因此强烈建议明确设置 bin 边缘。例如号码-0.5 - 0.50.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()

【讨论】:

  • 请注意,您也可以使用 seaborn 的 countplot 获取每个值一个 bin
猜你喜欢
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多