是否可以将 x 轴刻度与 matplotlib 直方图中的相应条对齐?
Is it possible to align x-axis ticks with corresponding bars in a matplotlib histogram?
在绘制时间序列日期时,我试图绘制每小时的数据点数:
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()
当您放置 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
,则会发生更奇怪的事情,因为范围将在遇到的最低值和最高值之间创建。
由于您的数据是离散的,因此强烈建议明确设置 bin 边缘。例如数字 -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()
在绘制时间序列日期时,我试图绘制每小时的数据点数:
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()
当您放置 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
,则会发生更奇怪的事情,因为范围将在遇到的最低值和最高值之间创建。
由于您的数据是离散的,因此强烈建议明确设置 bin 边缘。例如数字 -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()