2013-05-02 66 views
5

我想使用matplotlib繪製一個簡單的直方圖。我舉例(我將在實踐中使用不同的距離函數)Matplotlib直方圖(基本問題)

import matplotlib.pyplot as plt 
import numpy as np 
import itertools 


def hamdist(str1, str2): 
    """Count the # of differences between equal length strings str1 and str2""" 
    if (len(str1) != len(str2)): 
     print str1, str2, "Length mismatch bozo!!!!!!" 
    diffs = 0 
    for ch1, ch2 in itertools.izip(str1, str2): 
     if ch1 != ch2: 
      diffs += 1 
    return diffs 

n = 10 
bins=np.arange(0,n+2,1) 
hamdists = [] 
for str1 in itertools.product('01', repeat = n): 
    for str2 in itertools.product('01', repeat = n): 
     hamdists.append(hamdist(str1, str2)) 
plt.hist(hamdists, bins=bins) 
plt.show() 

我得到一個直方圖,看起來像這樣。

histogram

如何執行以下操作?

  1. 改變X軸,使最後一棒算個X = 10的數量。如果我只是改變bins=np.arange(0,11,1)這個切斷值X = 10
  2. 標籤的每一個點在x axis
  3. 將x軸標籤移動到條的中間,而不是像現在一樣將它們放在起始位置。

回答

15

您的第一個和第三個點可以通過設置直方圖函數的align關鍵字(默認爲'mid',bin的中心)來解決。第二個是通過手動設置xticks。

參見:

fig, ax = plt.subplots(1,1) 

ax.hist(hamdists, bins=bins, align='left') 
ax.set_xticks(bins[:-1]) 

enter image description here

+0

當我設置N = 10米使用倉= np.arange(0,N + 1,1)的x軸標籤仍然只上升到9 。 這是爲什麼?最後......我不希望有實際的蜱蟲,因爲它們在直方圖中令人困惑。 – marshall 2013-05-02 08:42:00

+0

因爲9是最後一個bin的開始。在你的帖子中,你說過你只想顯示開始,位於欄下方。實際上bin的範圍是從9到10.你可以通過捕獲hist函數的結果來探索結果: 'hist,bins,bars = ax.hist()' – 2013-05-02 08:57:49

+0

謝謝。所以9到10的一端不能包含在垃圾箱中。 – marshall 2013-05-02 09:02:27