如何通过特定步骤使 matplotlib 直方图与范围分开?
How do I make a mathplotlib histogram seperated with ranges by a specific step?
我想制作一个显示成绩的直方图(例如),并且我希望能够为 mathplotlib 指定一个特定的步长大小,以便从中生成 bin 范围。
例如,如果给定步长为 16,我希望直方图如下所示:
Example
我试过这样做:
def custom_histogram(lst, high_bound, low_bound, step):
bounds_dif = high_bound-low_bound
if bounds_dif%step == 0:
bin = int((high_bound-low_bound)/step)
else:
bin = int((high_bound-low_bound)/step) + 1
plt.hist(lst, bin, ec="white")
plt.show()
但随后范围被平分,而不是按步长划分(例如最后一个 bin 不是 96-100)。
解决方案
在matplotlib documentation中,它说:
If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open.
因此你可以这样做:
# The first and last bins will be inclusive
bins = list(range(0, max(lst), step) + [max(lst)]
plt.hist(lst, bins, ec="white")
如果您想保留保留自定义边界的可能性:
bins = list(range(low_bound, high_bound, step)) + [high_bound]
plt.hist(lst, bins, ec="white")
如何设置与最后一栏相同的宽度?
最后一根柱子可能比其他柱子细。诀窍是应用与另一个条相同的宽度。
# We need to get the Axe. This is one solution.
fig, ax = plt.subplots()
bins = list(range(low_bound, high_bound, step)) + [high_bound]
ax.hist(lst, bins, ec="white")
# Applies the width of the first Rectangle to the last one
ax.patches[-1].set_width(ax.patches[0].get_width())
之前:
之后:
我想制作一个显示成绩的直方图(例如),并且我希望能够为 mathplotlib 指定一个特定的步长大小,以便从中生成 bin 范围。
例如,如果给定步长为 16,我希望直方图如下所示: Example
我试过这样做:
def custom_histogram(lst, high_bound, low_bound, step):
bounds_dif = high_bound-low_bound
if bounds_dif%step == 0:
bin = int((high_bound-low_bound)/step)
else:
bin = int((high_bound-low_bound)/step) + 1
plt.hist(lst, bin, ec="white")
plt.show()
但随后范围被平分,而不是按步长划分(例如最后一个 bin 不是 96-100)。
解决方案
在matplotlib documentation中,它说:
If bins is a sequence, it defines the bin edges, including the left edge of the first bin and the right edge of the last bin; in this case, bins may be unequally spaced. All but the last (righthand-most) bin is half-open.
因此你可以这样做:
# The first and last bins will be inclusive
bins = list(range(0, max(lst), step) + [max(lst)]
plt.hist(lst, bins, ec="white")
如果您想保留保留自定义边界的可能性:
bins = list(range(low_bound, high_bound, step)) + [high_bound]
plt.hist(lst, bins, ec="white")
如何设置与最后一栏相同的宽度?
最后一根柱子可能比其他柱子细。诀窍是应用与另一个条相同的宽度。
# We need to get the Axe. This is one solution.
fig, ax = plt.subplots()
bins = list(range(low_bound, high_bound, step)) + [high_bound]
ax.hist(lst, bins, ec="white")
# Applies the width of the first Rectangle to the last one
ax.patches[-1].set_width(ax.patches[0].get_width())
之前:
之后: