【python海洋专题十三】读取多个nc文件画温度季节变化图

【python海洋专题十三】读取多个nc文件画温度季节变化图

上期内容
年平均的温度分布
【python海洋专题十三】读取多个nc文件画温度季节变化图_第1张图片

本期内容

读取多个文件;

拼接数据

在画温度的季节分布图

Part01.

使用数据

IAP 网格温度数据集

【python海洋专题十三】读取多个nc文件画温度季节变化图_第2张图片

Part02.

读取nc的函数包对比

from netCDF4 import Dataset
a = Dataset(filelist[1])
print(a)
import xarray as xr
f1 = xr.open_dataset(filelist[1])
print(f1)

上下都可以读取nc;通过对比打印的信息,建议使用xarray。效果如下:

print(a):

root group (NETCDF3_CLASSIC data model, file format NETCDF3):
    Title: IAP 3-Dimentional Subsurface Temperature Dataset Using Objective Analysis
    StartYear: 2021
    StartMonth: 2
    StartDay: 1
    EndYear: 2021
    EndMonth: 2
    EndDay: 30
    Period: 1
    GridProjection: Mercator, gridded
    GridPoints: 360x180
    Creator: Lijing Cheng From IAP,CAS,P.R.China
    Reference: Cheng and Zhu 2016. Journal of Climate; Cheng et al. 2017. Science Advances. Website for OHC: http://159.226.119.60/cheng/
    dimensions(sizes): lat(180), lon(360), time(1), depth_std(41)
    variables(dimensions): float32 lat(lat), float32 lon(lon), float32 time(time), float32 depth_std(depth_std), float32 temp(lat, lon, depth_std)
    groups: 

print(f1):

Dimensions:    (lat: 180, lon: 360, time: 1, depth_std: 41)
Coordinates:
  * lat        (lat) float32 -89.5 -88.5 -87.5 -86.5 ... 86.5 87.5 88.5 89.5
  * lon        (lon) float32 1.0 2.0 3.0 4.0 5.0 ... 357.0 358.0 359.0 360.0
  * time       (time) float32 2.021e+05
  * depth_std  (depth_std) float32 1.0 5.0 10.0 20.0 ... 1.7e+03 1.8e+03 2e+03
Data variables:
    temp       (lat, lon, depth_std) float32 ...
Attributes:
    Title:           IAP 3-Dimentional Subsurface Temperature Dataset Using O...
    StartYear:       2021
    StartMonth:      2
    StartDay:        1
    EndYear:         2021
    EndMonth:        2
    EndDay:          30
    Period:          1
    GridProjection:  Mercator, gridded
    GridPoints:      360x180
    Creator:         Lijing Cheng From IAP,CAS,P.R.China
    Reference:       Cheng and Zhu 2016. Journal of Climate; Cheng et al. 201...

图片
Part03.

海表面温度的季节变化图

图片
年平均

【python海洋专题十三】读取多个nc文件画温度季节变化图_第3张图片

春季:

【python海洋专题十三】读取多个nc文件画温度季节变化图_第4张图片

夏季:

【python海洋专题十三】读取多个nc文件画温度季节变化图_第5张图片

秋季:

【python海洋专题十三】读取多个nc文件画温度季节变化图_第6张图片

冬季:

【python海洋专题十三】读取多个nc文件画温度季节变化图_第7张图片

往期推荐

【python海洋专题一】查看数据nc文件的属性并输出属性到txt文件

【python海洋专题二】读取水深nc文件并水深地形图
【python海洋专题三】图像修饰之画布和坐标轴

【Python海洋专题四】之水深地图图像修饰

【Python海洋专题五】之水深地形图海岸填充

【Python海洋专题六】之Cartopy画地形水深图

【python海洋专题】测试数据

【Python海洋专题七】Cartopy画地形水深图的陆地填充

【python海洋专题八】Cartopy画地形水深图的contourf填充间隔数调整

【python海洋专题九】Cartopy画地形等深线图

【python海洋专题十】Cartopy画特定区域的地形等深线图

【python海洋专题十一】colormap调色

【python海洋专题十二】年平均的南海海表面温度图

全文代码

# -*- coding: utf-8 -*-
# %%
# Importing related function packages
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as feature
import numpy as np
import matplotlib.ticker as ticker
from cartopy import mpl
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from matplotlib.font_manager import FontProperties
from netCDF4 import Dataset
from pylab import *
import seaborn as sns
from matplotlib import cm
from pathlib import Path
import xarray as xr
import palettable
from palettable.cmocean.diverging import Delta_4
from palettable.colorbrewer.sequential import GnBu_9
from palettable.colorbrewer.sequential import Blues_9
from palettable.scientific.diverging import Roma_20
from palettable.cmocean.diverging import Delta_20
from palettable.scientific.diverging import Roma_20
from palettable.cmocean.diverging import Balance_20
from matplotlib.colors import ListedColormap




# ----define reverse_colourmap----
def reverse_colourmap(cmap, name='my_cmap_r'):
    reverse = []
    k = []

    for key in cmap._segmentdata:
        k.append(key)
        channel = cmap._segmentdata[key]
        data = []

        for t in channel:
            data.append((1 - t[0], t[2], t[1]))
        reverse.append(sorted(data))

    LinearL = dict(zip(k, reverse))
    my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL)
    return my_cmap_r


# ---colormap----
cmap01 = Balance_20.mpl_colormap
cmap0 = Blues_9.mpl_colormap
cmap_r = reverse_colourmap(cmap0)
cmap1 = GnBu_9.mpl_colormap
cmap_r1 = reverse_colourmap(cmap1)
cmap2 = Roma_20.mpl_colormap
cmap_r2 = reverse_colourmap(cmap2)
# -------------# 指定文件路径,实现批量读取满足条件的文件------------
filepath = Path('E:\data\IAP\IAP_gridded_temperature_dataset_v3\IAP_CZ16_2021\\')
filelist = list(filepath.glob('*.nc'))
print(filelist)
# -------------读取其中一个文件的经纬度数据,制作经纬度网格(这样就不需要重复读取)-------------------------
a = Dataset(filelist[1])
print(a)
# 随便读取一个文件(一般默认需要循环读取的文件格式一致)
f1 = xr.open_dataset(filelist[1])
print(f1)
# 提取经纬度(这样就不需要重复读取)
lat = f1['lat'].data
lon = f1['lon'].data
print(lat)
print(lon)
# -------- find scs 's temp-----------
print(np.where(lon >= 100))  # 99
print(np.where(lon >= 123))  # 122
print(np.where(lat >= 0))  # 90
print(np.where(lat >= 25))  # 115
# # 画图网格
lon1 = lon[100:123]
lat1 = lat[90:115]
X, Y = np.meshgrid(lon1, lat1)
print(X)
print(Y)
# ----------4.for循环读取文件+数据处理------------------
# for循环
tem_all = []
for file in filelist:
    with xr.open_dataset(file) as f:
        tem = f['temp'].data
        tem_mon = tem[90:115, 100:123, 1]  # 取表层sst
        tem_all.append(tem_mon)
print(len(tem_all))
# 1:12个月的温度:tem_all;
tem_year_mean = np.mean(tem_all, axis=0)
# 2:春季3-4-5
tem_all = np.array(tem_all)
tem_spr = (tem_all[2,:,:]+tem_all[3,:,:]+tem_all[4,:,:])/3
# 3:sum季6-7-8
tem_sum = (tem_all[5,:,:]+tem_all[6,:,:]+tem_all[7,:,:])/3
# 4:aut季9-10-11
tem_aut = (tem_all[8,:,:]+tem_all[9,:,:]+tem_all[10,:,:])/3
# 5:win季12-1-2
tem_win = (tem_all[0,:,:]+tem_all[1,:,:]+tem_all[11,:,:])/3
print(tem_all.shape)
# -------------# plot 年平均 ------------
scale = '50m'
plt.rcParams['font.sans-serif'] = ['Times New Roman']  # 设置整体的字体为Times New Roman
fig = plt.figure(dpi=300, figsize=(3, 2), facecolor='w', edgecolor='blue')  # 设置一个画板,将其返还给fig
ax = fig.add_axes([0.05, 0.08, 0.92, 0.8], projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 123, 0, 25], crs=ccrs.PlateCarree())  # 设置显示范围
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3)  # 添加海岸线:关键字lw设置线宽; lifestyle设置线型
cs = ax.contourf(X, Y, tem_year_mean, levels=np.linspace(20, 30, 50), extend='both', cmap=cmap_r2,
                 transform=ccrs.PlateCarree())
# ------color-bar设置------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=np.linspace(20, 30, 11))
cb.set_label('SST', fontsize=4, color='k')  # 设置color-bar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in')  # 设置color-bar刻度字体大小。
# cf = ax.contour(x, y, skt1[:, :], levels=np.linspace(16, 30, 5), colors='gray', linestyles='-',
#                 linewidths=0.2, transform=ccrs.PlateCarree())
# --------------添加标题----------------
ax.set_title('SST', fontsize=4)
# ------------------利用Formatter格式化刻度标签-----------------
ax.set_xticks(np.arange(100, 123, 4), crs=ccrs.PlateCarree())  # 添加经纬度
ax.set_xticklabels(np.arange(100, 123, 4), fontsize=4)
ax.set_yticks(np.arange(0, 25, 2), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 25, 2), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 刻度样式
ax.tick_params(axis='y', right=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 更改刻度指向为朝内,颜色设置为蓝色
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 123, 4), ylocs=np.arange(0, 25, 2),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8)  # 添加网格线
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
plt.savefig('scs_sst_2.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()

# -------------# plot spr------------
scale = '50m'
plt.rcParams['font.sans-serif'] = ['Times New Roman']  # 设置整体的字体为Times New Roman
fig = plt.figure(dpi=300, figsize=(3, 2), facecolor='w', edgecolor='blue')  # 设置一个画板,将其返还给fig
ax = fig.add_axes([0.05, 0.08, 0.92, 0.8], projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 123, 0, 25], crs=ccrs.PlateCarree())  # 设置显示范围
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3)  # 添加海岸线:关键字lw设置线宽; lifestyle设置线型
cs = ax.contourf(X, Y, tem_spr, levels=np.linspace(20, 30, 50), extend='both', cmap=cmap_r2,
                 transform=ccrs.PlateCarree())
# ------color-bar设置------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=np.linspace(20, 30, 11))
cb.set_label('SST', fontsize=4, color='k')  # 设置color-bar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in')  # 设置color-bar刻度字体大小。
# cf = ax.contour(x, y, skt1[:, :], levels=np.linspace(16, 30, 5), colors='gray', linestyles='-',
#                 linewidths=0.2, transform=ccrs.PlateCarree())
# --------------添加标题----------------
ax.set_title('SST', fontsize=4)
# ------------------利用Formatter格式化刻度标签-----------------
ax.set_xticks(np.arange(100, 123, 4), crs=ccrs.PlateCarree())  # 添加经纬度
ax.set_xticklabels(np.arange(100, 123, 4), fontsize=4)
ax.set_yticks(np.arange(0, 25, 2), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 25, 2), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 刻度样式
ax.tick_params(axis='y', right=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 更改刻度指向为朝内,颜色设置为蓝色
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 123, 4), ylocs=np.arange(0, 25, 2),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8)  # 添加网格线
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
plt.savefig('scs_sst_spr.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()

# -------------# plot sum------------
scale = '50m'
plt.rcParams['font.sans-serif'] = ['Times New Roman']  # 设置整体的字体为Times New Roman
fig = plt.figure(dpi=300, figsize=(3, 2), facecolor='w', edgecolor='blue')  # 设置一个画板,将其返还给fig
ax = fig.add_axes([0.05, 0.08, 0.92, 0.8], projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 123, 0, 25], crs=ccrs.PlateCarree())  # 设置显示范围
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3)  # 添加海岸线:关键字lw设置线宽; lifestyle设置线型
cs = ax.contourf(X, Y, tem_sum, levels=np.linspace(20, 30, 50), extend='both', cmap=cmap_r2,
                 transform=ccrs.PlateCarree())
# ------color-bar设置------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=np.linspace(20, 30, 11))
cb.set_label('SST', fontsize=4, color='k')  # 设置color-bar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in')  # 设置color-bar刻度字体大小。
# cf = ax.contour(x, y, skt1[:, :], levels=np.linspace(16, 30, 5), colors='gray', linestyles='-',
#                 linewidths=0.2, transform=ccrs.PlateCarree())
# --------------添加标题----------------
ax.set_title('SST', fontsize=4)
# ------------------利用Formatter格式化刻度标签-----------------
ax.set_xticks(np.arange(100, 123, 4), crs=ccrs.PlateCarree())  # 添加经纬度
ax.set_xticklabels(np.arange(100, 123, 4), fontsize=4)
ax.set_yticks(np.arange(0, 25, 2), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 25, 2), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 刻度样式
ax.tick_params(axis='y', right=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 更改刻度指向为朝内,颜色设置为蓝色
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 123, 4), ylocs=np.arange(0, 25, 2),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8)  # 添加网格线
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
plt.savefig('scs_sst_sum.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()


# -------------# plot aut------------
scale = '50m'
plt.rcParams['font.sans-serif'] = ['Times New Roman']  # 设置整体的字体为Times New Roman
fig = plt.figure(dpi=300, figsize=(3, 2), facecolor='w', edgecolor='blue')  # 设置一个画板,将其返还给fig
ax = fig.add_axes([0.05, 0.08, 0.92, 0.8], projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 123, 0, 25], crs=ccrs.PlateCarree())  # 设置显示范围
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3)  # 添加海岸线:关键字lw设置线宽; lifestyle设置线型
cs = ax.contourf(X, Y, tem_aut, levels=np.linspace(20, 30, 50), extend='both', cmap=cmap_r2,
                 transform=ccrs.PlateCarree())
# ------color-bar设置------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=np.linspace(20, 30, 11))
cb.set_label('SST', fontsize=4, color='k')  # 设置color-bar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in')  # 设置color-bar刻度字体大小。
# cf = ax.contour(x, y, skt1[:, :], levels=np.linspace(16, 30, 5), colors='gray', linestyles='-',
#                 linewidths=0.2, transform=ccrs.PlateCarree())
# --------------添加标题----------------
ax.set_title('SST', fontsize=4)
# ------------------利用Formatter格式化刻度标签-----------------
ax.set_xticks(np.arange(100, 123, 4), crs=ccrs.PlateCarree())  # 添加经纬度
ax.set_xticklabels(np.arange(100, 123, 4), fontsize=4)
ax.set_yticks(np.arange(0, 25, 2), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 25, 2), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 刻度样式
ax.tick_params(axis='y', right=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 更改刻度指向为朝内,颜色设置为蓝色
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 123, 4), ylocs=np.arange(0, 25, 2),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8)  # 添加网格线
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
plt.savefig('scs_sst_aut.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()


# -------------# plot win------------
scale = '50m'
plt.rcParams['font.sans-serif'] = ['Times New Roman']  # 设置整体的字体为Times New Roman
fig = plt.figure(dpi=300, figsize=(3, 2), facecolor='w', edgecolor='blue')  # 设置一个画板,将其返还给fig
ax = fig.add_axes([0.05, 0.08, 0.92, 0.8], projection=ccrs.PlateCarree(central_longitude=180))
ax.set_extent([100, 123, 0, 25], crs=ccrs.PlateCarree())  # 设置显示范围
land = feature.NaturalEarthFeature('physical', 'land', scale, edgecolor='face',
                                   facecolor=feature.COLORS['land'])
ax.add_feature(land, facecolor='0.6')
ax.add_feature(feature.COASTLINE.with_scale('50m'), lw=0.3)  # 添加海岸线:关键字lw设置线宽; lifestyle设置线型
cs = ax.contourf(X, Y, tem_win, levels=np.linspace(20, 30, 50), extend='both', cmap=cmap_r2,
                 transform=ccrs.PlateCarree())
# ------color-bar设置------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=np.linspace(20, 30, 11))
cb.set_label('SST', fontsize=4, color='k')  # 设置color-bar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in')  # 设置color-bar刻度字体大小。
# cf = ax.contour(x, y, skt1[:, :], levels=np.linspace(16, 30, 5), colors='gray', linestyles='-',
#                 linewidths=0.2, transform=ccrs.PlateCarree())
# --------------添加标题----------------
ax.set_title('SST', fontsize=4)
# ------------------利用Formatter格式化刻度标签-----------------
ax.set_xticks(np.arange(100, 123, 4), crs=ccrs.PlateCarree())  # 添加经纬度
ax.set_xticklabels(np.arange(100, 123, 4), fontsize=4)
ax.set_yticks(np.arange(0, 25, 2), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 25, 2), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(axis='x', top=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 刻度样式
ax.tick_params(axis='y', right=True, which='major', direction='in', length=4, width=1, labelsize=5, pad=1, color='k')  # 更改刻度指向为朝内,颜色设置为蓝色
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(100, 123, 4), ylocs=np.arange(0, 25, 2),
                  linewidth=0.25, linestyle='--', color='k', alpha=0.8)  # 添加网格线
gl.top_labels, gl.bottom_labels, gl.right_labels, gl.left_labels = False, False, False, False
plt.savefig('scs_sst_win.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()

参考文献

1:列表取片操作易错点(list indices must be integers or slices, not tuple原因及解决方法)-CSDN博客

2:Python绘图技巧3:批量读取nc文件 - Heywhale.com

3:每日一课 | 在Python中获取列表的长度和大小-CSDN博客

4:python中append函数的用法_append函数python-CSDN博客

你可能感兴趣的:(python,开发语言)