2017-05-31 34 views
-1

我的數據由多種波動率值組成,即0到1之間的小數。現在,只有6%和24%之間的值特別相關,因此我試圖構建一個直方圖來顯示相對計數這些價值。我想要一個直方圖,它具有0-6%,6-8%,... 22-24%,> 24%的分箱,但這證明是非常困難的。總共應該有11個垃圾箱,垃圾箱的標籤應該位於垃圾箱下方。 y軸不能有任何標籤,因爲只有相對計數很重要,並且包括y軸上的值會降低我試圖強調的相對性。如何在Matplotlib中手動指定垃圾箱?

我已經瘋狂接近能夠通過閱讀答案,如Matplotlib xticks not lining up with histogramBin size in Matplotlib (Histogram)

如果有人能幫我解決這個問題,我會非常感激。感謝您的幫助。

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
import matplotlib.path as path 

graph1, ax = plt.subplots() 

n, bins = np.histogram(values, 11) 

left = np.array(bins[:-1]) 
right = np.array(bins[1:]) 
bottom = np.zeros(len(left)) 
top = bottom + n 

XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T 

barpath = path.Path.make_compound_path_from_polys(XY) 

patch = patches.PathPatch(barpath, facecolor="blue", edgecolor="#FFFFFF", 
alpha = 0.75) 
ax.add_patch(patch) 

ax.set_xlim(left[0], right[-1]) 
ax.set_ylim(bottom.min(), top.max()) 

graph1.suptitle("1-Year Rolling Volatilities") 
ax.axes.get_yaxis().set_visible(False) 

plt.show() 

這幾乎產生正確的直方圖,但桶是不是我想要的時間間隔內,xticks不集中,並沒有對每個箱一個標籤。

+0

您需要顯示一些代碼並解釋輸出與所需內容的不同之處。 – BrenBarn

+0

我認爲我使用的代碼與我實際需要的代碼相距太遠。我主動選擇不發佈代碼,因爲我不希望有人按照我已經使用過的方式工作。如果你真的認爲我應該包括我的代碼,我會發布它,但我想要一個全新的解決方案,而不是對我已有的東西的調整。我不喜歡我用過的方法,新的解決方案只能比我的方法更好 –

+0

不,你不是想發佈*你的*代碼,而是問題的[mcve]。 – ImportanceOfBeingErnest

回答

0
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
import matplotlib.path as path 

graph1, ax = plt.subplots() 

values = [0.15, 0.23, 0.061, 0.085, 0.06, 0.09, 0.07, 0.05, 0.04, 0.08] 
#n, bins = np.histogram(values, 11) 
plt.hist(values, bins=[0, 0.06, 0.08, 0.22, 0.24, 1.00]) 

您也可以使用類似的東西來設置您的垃圾箱下方的勾號。有關在此堆棧溢出設置刻度的更多信息Matplotlib - label each bin

+0

是的,這很接近,我也希望能成爲解決方案,但這不太合適。我無法簡單列出垃圾箱邊緣。此外,現在代碼已經啓動,但我不確定我是應該使用numpy.histogram()還是plt.hist(),我會使用哪一種更簡單。 –

+0

雖然您發佈了代碼,但我不能在我的系統上運行它。所以我無法測試一些東西。它表示未定義的名稱路徑,補丁,值等。 – Dest

+0

我剛剛列入相關進口 –