2016-08-23 175 views
0

當在Matplotlib中創建堆疊直方圖時,我注意到bin寬度縮小。在這個簡單的例子:Matplotlib堆疊直方圖bin寬度

import numpy as np 
import matplotlib 
import matplotlib.pylab as plt 

#Create histograms and plots 
fig = plt.figure() 
gs = matplotlib.gridspec.GridSpec(1, 2) 
h1 = fig.add_subplot(gs[0]) 
h2 = fig.add_subplot(gs[1]) 

x = np.random.normal(0, 5, 500) 
y = np.random.normal(0, 20, 500) 

bins = np.arange(-60,60, 5) 

h1.hist([x, y], bins=bins, stacked=True) 
h2.hist(x, bins=bins, alpha=1) 
h2.hist(y, bins=bins, alpha=0.5) 

plt.tight_layout() 
plt.show() 
filename = 'sample.pdf' 
plt.savefig(filename) 

我得到以下輸出:

enter image description here

注意左邊的直方圖具有即使兩個左右直方圖使用的是每個容器之間的間距相同的箱子。

有沒有辦法糾正這種行爲?我希望左邊的直方圖使用滿箱寬度,以便相鄰箱共享一個邊。

回答

0

如果ax.hist -call的第一個參數是一個列表(或二維numpy數組或兩者的組合)的列表,它會自動使得bin變小。 ax.hist-call的rwidth參數是決定bin-width的參數。將其設置爲1會做你想要它做的事情:

h1.hist([x, y], bins=bins, stacked=True, rwidth=1)

+0

謝謝你的回覆。你知道爲什麼默認行爲是縮小垃圾箱嗎? – jadenkorr