2014-02-13 54 views
1

我試圖運行下面的代碼:疊加柱狀圖不會疊加

variable_values = #numpy vector, one dimension, 5053 values between 1 and 0. 
label_values = #numpy vector, one dimension, 5053 values, discrete value of either 1 OR 0. 
x = variable_values[variable_values != '?'].astype(float) 
y = label_values[variable_values != '?'].astype(float) 

print np.max(x) #prints 0.90101 
print np.max(y) #prints 1.0 


N = 5053 
ind = np.arange(N) # the x locations for the groups 
width = 0.45  # the width of the bars: can also be len(x) sequence 
n, bins, patches = plt.hist(x, 5, stacked=True, normed = True) 

#Stack the data 
plt.figure() 
plt.hist(x, bins, stacked=True, normed = True) 
plt.hist(y, bins, stacked=True, normed = True) 
plt.show() 

我想實現如下圖:

enter image description here

隨着各條分割的顏色根據其是否爲label的值爲1或0.

不幸的是我的輸出當前是:

Output

有兩件事情不正確使用此 - 它不是堆疊適當首先的。其次,Y軸上的值上升到1.6,但我相信Y軸應該包含落入每個子組的數據數量(因此,如果所有數據段的值都是0-0.25,將顯示數據的酒吧將是第一個)。

+0

這是一個直方圖..最高峯將是最頻繁的價值,而不是最大的價值。 – M4rtini

+0

@ M4rtini對不起,是的,你說得對 - 這是爲什麼在這裏打印出最大值1.6?理想情況下,Id喜歡將5053條數據拆分爲四個條(Y軸上顯示數據的數量),並將條分割爲數字,其中標籤== 1和標籤== 0。道歉,我對自己的問題感到困惑。現在會更新。 –

回答

2

variable_values = #numpy向量,一個尺寸,1和0之間的值5053

label_values = #numpy向量,一個維度,5053個值,離散值 1或0。

您試圖對x和y使用相同的bin。 x可能是從0-1不包括邊緣。因此,y落在您正在繪製的垃圾箱範圍之外。

這是1.6,因爲你選擇了規範的情節。將該參數設置爲false以獲取實際計數。

這應該可以解決大部分問題:

import numpy as np 
import matplotlib.pyplot as plt 

x = np.random.random(5053) 
y = np.random.random_integers(0,1, 5053) 

# x = variable_values[variable_values != '?'].astype(float) 
# y = label_values[variable_values != '?'].astype(float) 

print np.max(x) #prints 0.90101 
print np.max(y) #prints 1.0 


N = 5053 
ind = np.arange(N) # the x locations for the groups 
width = 0.45  # the width of the bars: can also be len(x) sequence 
n, bins, patches = plt.hist(x, 5, stacked=True, normed = True) 

bins[0] = 0 
bins[-1] = 1 

#Stack the data 
plt.figure() 
plt.hist(y, bins, stacked=True, normed = False) 
plt.hist(x, bins, stacked=True, normed = False) 
plt.show() 
2

我可以提出一個更簡單的解決方案:

variable_values=np.random.random(size=5053) 
label_values=np.random.randint(0,2, size=5053) 
plt.hist(variable_values, label='1') 
plt.hist(variable_values[label_values==0], label='0') 
plt.legend(loc='upper right') 
plt.savefig('temp.png') 

enter image description here

實際上由於label_values是1或0,你甚至不需要堆疊直方圖。只需製作1和0的直方圖,然後在頂部疊加0的直方圖。

要使用堆棧柱狀圖,雖然我寧願只有當有許多不同的類:

plt.hist([variable_values[label_values==1],variable_values[label_values==0]], stacked=True, label=['1', '0'])