import rasterio
import numpy as np
import matplotlib.pyplot as plt
# 读取两个变量的tif文件
tif_file_1 = 'F:/ecosystem services_out/2020/sd20.tif'
tif_file_2 = 'F:/ecosystem services_out/2020/wy20.tif'
# 读取栅格数据
with rasterio.open(tif_file_1) as src:
data_1 = src.read(1)
profile = src.profile
nodata_value_1 = src.nodata
with rasterio.open(tif_file_2) as src:
data_2 = src.read(1)
nodata_value_2 = src.nodata
# 将nodata值替换为numpy.nan
data_1[data_1 == nodata_value_1] = np.nan
data_2[data_2 == nodata_value_2] = np.nan
# 确保两个数据集具有相同的形状
assert data_1.shape == data_2.shape, "两个数据集的形状不匹配"
# 计算每个像素点的相关系数
mean_1 = np.nanmean(data_1)
mean_2 = np.nanmean(data_2)
std_1 = np.nanstd(data_1)
std_2 = np.nanstd(data_2)
correlation_spatial_map = (data_1 - mean_1) * (data_2 - mean_2) / (std_1 * std_2)
# 保存相关系数空间分布图为tif文件
output_tif = 'F:/ecosystem services_out/correlation_sd20_wy20.tif'
with rasterio.open(output_tif, 'w', **profile) as dst:
correlation_spatial_map[np.isnan(correlation_spatial_map)] = profile["nodata"]
dst.write(correlation_spatial_map, 1)
# 绘制相关系数空间分布图(忽略nodata值)
plt.imshow(correlation_spatial_map, cmap='coolwarm', vmin=-1, vmax=1)
plt.colorbar(label='相关系数')
plt.title('相关系数空间分布图')
plt.show()
用于子流域的:
子流域
library(spgwr)
library(rgdal)
library(sf)
library(spData)
library(sp)
library(lattice)
library(ggplot2)
library(ggthemes)
library(GWmodel)
setwd("C:/Users/qkz952/Desktop/Published outputs/Courses/SOM_GWR")
ES <- readOGR(dsn = "C:/Users/qkz952/Desktop/Published outputs/Courses/SOM_GWR", layer = "Watershed")
bw.AB<-bw.gwr(A~B,data = ES)
#A function for automatic bandwidth selection to calibrate a basic GWR model
AB<-gwr.basic(A~B,data=ES,bw=bw.AB)
gwr.write(AB,fn="AB")
然后是GWR的:
##########################################
#####Geographical weighted regression####
##########################################
library(spgwr)
library(rgdal)
library(sf)
library(spData)
library(sp)
library(lattice)
library(ggplot2)
library(ggthemes)
library(GWmodel)
setwd("C:\Users\12939\Desktop\G2\fig.5gwr\00")
ES <- readOGR(dsn = "C:\Users\12939\Desktop\G2\fig.5gwr\00", layer = "Watershed")
bw.AB<-bw.gwr(A~B,data = ES)
#A function for automatic bandwidth selection to calibrate a basic GWR model
AB<-gwr.basic(A~B,data=ES,bw=bw.AB)
gwr.write(AB,fn="AB")
附自己的发表论文图片:
