[英]How to draw histogram with same bins width for unequally spaced bins in matplotlib
[英]How to draw a histogram with variable-width bins in Python?
假設我有數據[1,2,3, 7,8,9,9, 20,30,40,100,1000] ,我想用 Python 為其繪制直方圖。 我關心的所有箱子都是[0,5]、[5,10] 和 [10, +∞) 。 我該怎么做?
當然,以下不會這樣做。
import matplotlib.pyplot as plt
data = [1,2,3, 7,8,9,9, 20,30,40,100,1000]
plt.figure()
plt.hist(data, bins=5, color="rebeccapurple")
plt.show()
如果強制顯示具有自定義 x 范圍的直方圖,您可能需要先處理數據。
我制作了一個范圍列表以及 x_ticklabels 以顯示 x 軸和范圍。
import matplotlib.pyplot as plt
import numpy as np
data = [1,2,3, 7,8,9,9, 20,30,40,100,1000,500,200]
data = np.array(data)
bin_range = [
[0, 5],
[5, 10],
[10, 10000] # enough number to cover range
]
data2plot = np.zeros(len(bin_range))
for idx, (low, high) in enumerate(bin_range):
data2plot[idx] = ((low <= data) & (data < high)).sum()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(range(len(bin_range)), data2plot)
x_labels = [
f"{low}~{high}" for idx, (low, high) in enumerate(bin_range)
]
ax.set_xticks(range(len(bin_range)))
ax.set_xticklabels(x_labels)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.