簡體   English   中英

plot直方圖,當給定區間值的數量時? (Python)

[英]How to plot histogram, when the number of values in interval is given? (python)

我知道當您通常使用直方圖 plot 時,您會得到一組值和間隔。 但是如果我有間隔和這些間隔中的值的數量,我怎么能 plot 直方圖?

我有一些看起來像這樣的東西:

amounts = np.array([23, 7, 18, 5])

我的間隔是從 0 到 4,步驟 1,所以在間隔 [0,1] 上有 23 個值,依此類推。

您可以為此嘗試matplotlib.pyplot.stairs

import matplotlib.pyplot as plt
import numpy as np

amounts = np.array([23, 7, 18, 5])
plt.stairs(amounts, range(5))

plt.show()

如果有幫助,請將其標記為已解決。

我發現更容易模擬一些具有所需分布的數據,然后使用plt.hist到 plot 直方圖。

這是我的例子。 希望它會有所幫助!

import numpy as np
import matplotlib.pyplot as plt


amounts = np.array([23, 7, 18, 5])
bin_edges = np.arange(5)
bin_centres = (bin_edges[1:] + bin_edges[:-1]) / 2

# fake some data having the desired distribution
data = [[bc] * amount for bc, amount in zip(bin_centres, amounts)]
data = np.concatenate(data)

hist = plt.hist(data, bins=bin_edges, histtype='step')[0]
plt.show()

# the plotted distribution is consistent with amounts
assert np.allclose(hist, amounts)

如果您已經知道這些值,則直方圖將變成條形 plot。

amounts = np.array([23, 7, 18, 5])
interval = np.arange(5)
midvals = (interval + 0.5)[0:len(vals)-1] # 0.5, 1.5, 2.5, 3.5

plt.bar(midvals, 
    amounts)
plt.xticks(interval) # Shows the interval ranges rather than the centers of the bars

plt.show()

條形圖/直方圖

如果條形之間的間隙看起來很寬,您可以通過將width (作為 1 的分數 - 默認值為 0.8)參數傳遞給plt.bar()來更改條形的寬度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM