最近研究南海海温时用到了这个,向大家进行一个代码分享
需要:catorpy,numpy,scipy
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import pearsonr
def LCC(data1, data2, n, path):
# 作滞后相关,n>0时,data2先于data1发生
# 如data2为海温,data1为降水,n为1——>LCC为海温关于当年降水和来年降水的相关
a = n * 2 + 1
b = len(data1)
x = np.arange(-n, n + 1, 1)
r = np.zeros((a))
p = np.zeros((a))
for i in range(a):
if i < (n):
r[n - i - 1], p[n - i - 1] = pearsonr(data1[:(b - i - 1)], data2[i + 1:])
else :
r[i], p[i] = pearsonr(data1[x[i]:], data2[:b - x[i]])
# 画图
fig = plt.figure()
ax = fig.add_subplot(111)
ax.axhline(0,linewidth=3, color='k') #零刻度线
cs = ax.bar(x[n:], r[n:], align='center',edgecolor='k',linewidth=3,color = 'white')
# 从无滞后相关开始绘图,对齐方式为中心对齐
count = n
for bar, height in zip(cs, r): #开始显著性检验
if p[count] < 0.01:
bar.set(hatch='///') #通过99%的显著性检验为斜线
if p[count] < 0.005:
bar.set(hatch='||') #通过99.5%的显著性检验为竖线
if p[count] < 0.001:
bar.set(hatch='--') #通过99.9%的显著性检验为横线
count = count+1
ax.bar_label(cs) #标注
plt.title('cor_max='+ str(np.max(r))+'\n'+'cor_min='+str(np.min(r)))
plt.show()
plt.savefig(path)
plt.close()