[英]How do I make a mathplotlib histogram seperated with ranges by a specific step?
我想制作一個顯示成績的直方圖(例如),並且我希望能夠給 mathplotlib 一個特定的步長,以使 bin 范圍從中。
例如,如果給定的步長為 16,我希望直方圖看起來像這樣:示例
我嘗試這樣做:
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 文檔中,它說:
如果 bins 是一個序列,它定義了 bin 的邊界,包括第一個 bin 的左邊界和最后一個 bin 的右邊界; 在這種情況下,bin 的間距可能不等。 除了最后一個(最右邊的)垃圾箱外,所有垃圾箱都是半開的。
因此你可以這樣做:
# 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())
前 :
后 :
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.