2015-10-27 101 views
1

我喜歡我的繪製直方圖是這樣的:如何繪製np.histogram的結果與matplotlib模擬plt.hist

data = [-0.5, 0.5, 0.5, 0.5, 
    1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2] 

plt.hist(data, bins=5, range=[-1, 4], histtype='step') 

現在,當我有(比我的記憶大)莫名其妙地大量輸入數據,我需要用塊填充直方圖塊。例如。是這樣的:

H, bins = np.histogram([], bins=5, range=[-1, 4]) 
for data in a_lot_of_input_files: 
    H += np.histogram(data, bins=5, range=[-1, 4])[0] 

但問題始終是,「怎樣才能再次繪製此H,所以它看起來就像以前matplotlib版本

我想出了一個解決方案,看起來是這樣的:

plt.plot(bins, np.insert(H, 0, H[0]), '-', drawstyle='steps') 

Two different versions of plotting a histogram.

然而,無論是外觀的結果是相同的,也不會覺得很不錯創造副本繪製它的。

有沒有一些優雅的解決方案,我失蹤了? (我還沒有嘗試使用plt.bar,因爲條形圖不能很好地工作,當你想比較直方圖時)

+0

你嘗試使用一個大問題堆積的酒吧情節?你可以疊加單個直方圖,並給它們全部相同的面孔,所以它看起來像一個單一的條形圖...看看[matplotlib示例庫](http://matplotlib.org/examples/ pylab_examples/bar_stacked.html)。 – jkalden

+0

你可以通過查看''plt.hist'的[源代碼](https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_axes.py#L5686) ':你會看到那裏有很多邏輯,所以你不可能在不重複邏輯的情況下精確地複製輸出。 – jakevdp

+0

用plt.hist直接繪製直方圖並用plt.plot + np.histogram繪圖應該會產生相同的結果。 np.histogram會給你非整數值看起來很奇怪。爲避免複製數組,您可以省略箱的開始或結束值。 – DanHickstein

回答

1

不確定你的意思是「條形圖不能很好地工作,當一個要比較直方圖」,

的一種方式做,這是與plt.bar

import matplotlib.pyplot as plt 
import numpy as np 

data = [-0.5, 0.5, 0.5, 0.5, 
    1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2] 

plt.hist(data, bins=5, range=[-1, 4], histtype='step',edgecolor='r',linewidth=3) 
H, bins = np.histogram(data[:6], bins=5, range=[-1, 4]) 
H+=np.histogram(data[6:], bins=5,range=[-1, 4])[0] 

plt.bar(bins[:-1],H,width=1) 

plt.show() 

enter image description here

另一種方法是plt.step

import matplotlib.pyplot as plt 
import numpy as np 

data = [-0.5, 0.5, 0.5, 0.5, 
    1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2] 

plt.hist(data, bins=5, range=[-1, 4], histtype='step',edgecolor='r') 
H, bins = np.histogram(data[:6], bins=5, range=[-1, 4]) 
H+=np.histogram(data[6:], bins=5,range=[-1, 4])[0] 

bincentres = [(bins[i]+bins[i+1])/2. for i in range(len(bins)-1)] 
plt.step(bincentres,H,where='mid',color='b',linestyle='--') 

plt.ylim(0,6) 

plt.show() 

邊緣不太一路延伸,所以你可能需要一個0-bin到兩端,如果這就是你

enter image description here