2017-05-25 91 views
1

我的問題是如何關聯我的兩個binned圖並輸出Pearson相關係數?Python(numpy) - 關聯兩個binned圖

我不知道如何正確提取np.corrcoef函數所需的合併數組。這裏是我的腳本:

import numpy as np 
import matplotlib.pyplot as plt 

A = np.genfromtxt('data1.txt') 
x1 = A[:,1] 
y1 = A[:,2] 

B=np.genfromtxt('data2.txt') 
x2 = B[:,1] 
y2 = B[:,2] 

fig = plt.figure() 
plt.subplots_adjust(hspace=0.5) 
plt.subplot(121) 
AA = plt.hexbin(x1,y1,cmap='jet',gridsize=500,vmin=0,vmax=450,mincnt=1) 
plt.axis([-180,180,-180,180]) 
cb = plt.colorbar() 
plt.title('Data1') 

plt.subplot(122) 
BB = plt.hexbin(x2,y2,cmap='jet',gridsize=500,vmin=0,vmax=450,mincnt=1) 
plt.axis([-180,180,-180,180]) 
cb = plt.colorbar() 
plt.title('Data 2') 

array1 = np.ndarray.flatten(AA) 
array2 = np.ndarray.flatten(BB) 

print np.corrcoef(array1,array2) 

plt.show() 

回答

1

答案可以在documentation發現:

返回:對象

一個PolyCollection實例;在此PolyCollection上使用get_array()來獲取每個六邊形中的計數。

這裏是你的代碼的修訂版:雖然

A = np.genfromtxt('data1.txt') 
x1 = A[:,1] 
y1 = A[:,2] 

B = np.genfromtxt('data2.txt') 
x2 = B[:,1] 
y2 = B[:,2] 

# make figure and axes 
fig, (ax1, ax2) = plt.subplots(1, 2) 

# define common keyword arguments 
hex_params = dict(cmap='jet', gridsize=500, vmin=0, vmax=450, mincnt=1) 

# plot and set titles 
hex1 = ax1.hexbin(x1, y1, **hex_params) 
hex2 = ax2.hexbin(x2, y2, **hex_params) 
ax1.set_title('Data 1') 
ax2.set_title('Data 2') 

# set axes lims 
[ax.set_xlim(-180, 180) for ax in (ax1, ax2)] 
[ax.set_ylim(-180, 180) for ax in (ax1, ax2)] 

# add single colorbar 
fig.subplots_adjust(right=0.8, hspace=0.5) 
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) 
fig.colorbar(hex2, cax=cbar_ax) 

# get binned data and corr coeff 
binned1 = hex1.get_array() 
binned2 = hex2.get_array()  
print np.corrcoef(binned1, binned2) 

plt.show() 

兩點意見:你確定你想要的Pearson相關係數?你究竟想展示什麼?如果您想要顯示分佈是相同/不同的,您可能需要使用Kolmogorov-Smirnov測試。

也不要使用jet作爲顏色映射。 Jet is bad

+0

謝謝你的腳本 - 同樣,感謝您提供KS測試,您是對的,它是比較分佈更加嚴格的方法。 – EA00