2012-07-17 21 views
11

我使用條形圖來指示每個組的數據。這些欄中的一些與其他欄有很大不同。我怎樣才能指出條形圖中的顯着差異?指示條形圖中的統計顯着差異

import numpy as np 
import matplotlib.pyplot as plt 
menMeans = (5, 15, 30, 40) 
menStd  = (2, 3, 4, 5) 
ind = np.arange(4) # the x locations for the groups 
width=0.35 
p1 = plt.bar(ind, menMeans, width=width, color='r', yerr=menStd) 
plt.xticks(ind+width/2., ('A', 'B', 'C', 'D')) 

我的目標爲

enter image description here

+0

是唯一比較,進行局部相鄰?也就是說,你是否只想顯示'(A,B)(B,C)(C,D)'而不是'(A,C)'之間的區別? – Hooked 2012-07-17 19:24:06

+0

不,我想對所有可能的配對進行比較。 – imsc 2012-07-17 19:46:56

+1

可能很難在圖表上顯示,特別是如果有大量項目。如果你有N = 10,項目有45個不同的成對比較!看起來你可以在矩陣上顯示你的成對p值。這會工作嗎? – Hooked 2012-07-17 19:56:32

回答

14

我已經做了幾件事情在這裏,我與複雜的情節中工作時建議。將自定義格式拉出到字典中,當您想要更改參數時,它使生活變得簡單 - 並且您可以將該字典傳遞給多個圖。我還寫了一個自定義函數給0123eritervalues,作爲一個獎勵,它可以在(A,C)之間註釋,如果你真的想(我堅持認爲這不是正確的視覺方法)。一旦數據發生變化,可能需要進行一些調整,但這應該會讓你走上正軌。

import numpy as np 
import matplotlib.pyplot as plt 
menMeans = (5, 15, 30, 40) 
menStd  = (2, 3, 4, 5) 
ind = np.arange(4) # the x locations for the groups 
width= 0.7 
labels = ('A', 'B', 'C', 'D') 

# Pull the formatting out here 
bar_kwargs = {'width':width,'color':'y','linewidth':2,'zorder':5} 
err_kwargs = {'zorder':0,'fmt':None,'linewidth':2,'ecolor':'k'} #for matplotlib >= v1.4 use 'fmt':'none' instead 

fig, ax = plt.subplots() 
ax.p1 = plt.bar(ind, menMeans, **bar_kwargs) 
ax.errs = plt.errorbar(ind, menMeans, yerr=menStd, **err_kwargs) 


# Custom function to draw the diff bars 

def label_diff(i,j,text,X,Y): 
    x = (X[i]+X[j])/2 
    y = 1.1*max(Y[i], Y[j]) 
    dx = abs(X[i]-X[j]) 

    props = {'connectionstyle':'bar','arrowstyle':'-',\ 
       'shrinkA':20,'shrinkB':20,'linewidth':2} 
    ax.annotate(text, xy=(X[i],y+7), zorder=10) 
    ax.annotate('', xy=(X[i],y), xytext=(X[j],y), arrowprops=props) 

# Call the function 
label_diff(0,1,'p=0.0370',ind,menMeans) 
label_diff(1,2,'p<0.0001',ind,menMeans) 
label_diff(2,3,'p=0.0025',ind,menMeans) 


plt.ylim(ymax=60) 
plt.xticks(ind, labels, color='k') 
plt.show() 

enter image description here

+1

非常感謝。非常豐富。我只是把'ax.annotate(text,xy =(X [i],y + 7),zorder = 10)'改成'ax.annotate(text,xy =(x,y + 7),zorder = 10) '使p值居中。 – imsc 2012-07-18 15:28:33

+0

@imsc這就是我最初使用的,但這是文本塊左側的位置 - 而不是文本塊的中心。對我來說,這似乎與該位置略有偏離。無論哪種方式,我希望你看到你可以調整! – Hooked 2012-07-18 15:49:27

+1

噢,我也把'ha ='center''放在'annotate'中。 – imsc 2012-07-18 16:38:52