2017-06-22 38 views
1

說我有一個倉邊數組和一個倉值數組。 (基本上是plt.hist的輸出)。例如:繪製給定倉端點和值的直方圖

bins = np.array([1, 2, 3, 4, 5]) 
vals = np.array([2, 5, 5, 2]) 

我該如何繪製直方圖?

編輯:爲清楚起見,我的意思是丘壑是每個bin,其中LEN(瓦爾斯)+ 1 = LEN(箱)

回答

1

如果您正在使用python 3.5可以使用pyplotfill_between功能的「高度」這樣。您可以使用下面的代碼:

import numpy as np 
import matplotlib.pyplot as plt 
bins = np.array([1, 2, 3, 4, 5]) 
vals = np.array([2, 5, 5, 2]) 

plt.fill_between(bins,np.concatenate(([0],vals)), step="pre") 
plt.show() 

這將產生如下圖: graph with step command

+0

這是不正確的,因爲它會產生一個使用'vals'作爲輸入'x'值的直方圖,而不是OP請求的bin bar的實際高度。 – Gabriel

+1

你是對的@加布裏埃爾。我錯誤地理解OP想要從這些值生成直方圖。我更新了答案以對應問題的答案。我從另一個答案中添加了一個不同的選項。不幸的是,它只適用於'python 3.5'。 –

0

您可以使用bar情節:

enter image description here

bins = np.array([1, 2, 3, 4, 5]) 
vals = np.array([2, 5, 5, 2]) 
plt.bar((bins[1:] + bins[:-1]) * .5, vals, width=(bins[1] - bins[0])) 
plt.show() 

訣竅是使用您的「邊緣」的中點(bins[1:] + bins[:-1]) * .5,並將寬度設置爲(bins[1] - bins[0])明白你的整個直方圖都有不變的寬度。