|
发表于 2023-4-17 09:31:33
|
显示全部楼层
本帖最后由 歌者文明清理员 于 2023-4-17 09:34 编辑
以下是 MATLAB 读取气温 nc 文件并生成逐年逐站点平均气温的代码示例:
% 指定 nc 文件路径
filename = 'path/to/temperature_file.nc';
% 读取 nc 文件中某一个变量(这里假设为气温变量)
temp = ncread(filename, 'temperature');
% 获取参考时间的起始日期
ref_date = ncreadatt(filename, '/', 'units');
ref_date_str = extractAfter(ref_date, 'since ');
ref_date_val = datetime(ref_date_str);
% 读取站点的经纬度信息和站名
lat = ncread(filename, 'latitude');
lon = ncread(filename, 'longitude');
station_names = ncread(filename, 'station_name');
% 计算每个站点每年的平均气温
[n_stations, n_years] = size(temp);
annual_mean_temp = zeros(n_stations, n_years);
for i = 1:n_stations
for j = 1:n_years
year_temp = temp(i, (12*(j-1)+1):(12*j)); % 提取一年中的气温数据
annual_mean_temp(i,j) = mean(year_temp(year_temp > -999)); % 计算有效气温的平均值
end
end
% 生成逐年逐站点平均气温的热力图(需要安装 Mapping Toolbox)
figure
worldmap('World')
load('coastlines')
plotm(coastlat, coastlon)
cmap = jet(256);
colormap(cmap)
title('Annual Mean Temperature')
for i = 1:n_stations
lat_idx = find(abs(lat(i)-coastlat) == min(abs(lat(i)-coastlat)));
lon_idx = find(abs(lon(i)-coastlon) == min(abs(lon(i)-coastlon)));
if ~isempty(lat_idx) && ~isempty(lon_idx)
color_idx = round((annual_mean_temp(i,1)-min(annual_mean_temp(:)))/(max(annual_mean_temp(:))-min(annual_mean_temp(:)))*255)+1; % 计算颜色索引
scatterm(lat(i), lon(i), 10, cmap(color_idx,:), 'filled', 'MarkerEdgeColor', 'k')
textm(lat(i), lon(i), station_names(i,:), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle')
end
end
如果你需要绘制每个站点的逐年气温分布图,可以使用 boxplot 函数:
% 绘制逐年逐站点气温分布箱线图
figure
for i = 1:n_stations
subplot(ceil(sqrt(n_stations)),ceil(sqrt(n_stations)),i);
boxplot(squeeze(temp(i,:,:)), 'Labels', (ref_date_val.Year+1):(ref_date_val.Year+n_years), 'Whisker', 2.3);
title(station_names(i, :))
end
suptitle('Station Temperature Distribution')
如果你需要绘制整个区域内所有站点的气温分布图,可以使用 histogram2 函数:
% 绘制整个区域内所有站点的气温分布图(需要安装 Statistics and Machine Learning Toolbox)
figure
histogram2(lon(:), lat(:), 'BinMethod', 'fd', 'FaceColor', 'flat')
colormap(jet)
colorbar
xlabel('Longitude')
ylabel('Latitude')
zlabel('Temperature')
title('Temperature Distribution')
这是生成站点温度分布可以使用 scatterm 函数:
% 绘制整个区域内所有站点的气温散点图(需要安装 Mapping Toolbox)
figure
worldmap('World')
load('coastlines')
plotm(coastlat, coastlon)
cmap = jet(256);
colormap(cmap)
title('Temperature Distribution')
for i = 1:n_stations
lat_idx = find(abs(lat(i)-coastlat) == min(abs(lat(i)-coastlat)));
lon_idx = find(abs(lon(i)-coastlon) == min(abs(lon(i)-coastlon)));
if ~isempty(lat_idx) && ~isempty(lon_idx)
color_idx = round((annual_mean_temp(i,1)-min(annual_mean_temp(:)))/(max(annual_mean_temp(:))-min(annual_mean_temp(:)))*255)+1; % 计算颜色索引
scatterm(lat(i), lon(i), 10, cmap(color_idx,:), 'filled', 'MarkerEdgeColor', 'k')
textm(lat(i), lon(i), station_names(i,:), 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle')
end
end
请注意,这些示例代码可能需要根据你的实际数据情况进行一定的修改。 |
|