【python海洋专题十二】年平均的南海海表面温度图
上期内容
南海水深图
本期内容
年平均的南海平面温度图
数据来源
NCEP/DOE Reanalysis II: NOAA Physical Sciences Laboratory NCEP/DOE Reanalysis II
skt.skt.sfc.mon.ltm.nc
Part01.
本文重点内容
前几期地形图,不涉及时间维度,本次温度多了一个维度。因此,需要对时间维度进行平均,所以。
重点为平均:
skt的时间维度在第一个
skt_mean = np.nanmean(skt, axis=0)np.mean(a, # 必须是数组
axis=None,
dtype=None,
out=None,
keepdims=)
mean()函数的功能是求取平均值,经常操作的参数是axis,以m*n的矩阵为例:
axis不设置值,对m*n个数求平均值,返回一个实数
axis = 0:压缩行,对各列求均值,返回1*n的矩阵
axis = 1: 压缩列,对各行求均值,返回m*1的矩阵
数据二:
Index of /Datasets/noaa.ersst.v5
数据二的分辨率我感觉不高哈!看下图:
往期推荐
【python海洋专题一】查看数据nc文件的属性并输出属性到txt文件
【python海洋专题二】读取水深nc文件并水深地形图
【python海洋专题三】图像修饰之画布和坐标轴
【Python海洋专题四】之水深地图图像修饰
【Python海洋专题五】之水深地形图海岸填充
【Python海洋专题六】之Cartopy画地形水深图
【python海洋专题】测试数据
【Python海洋专题七】Cartopy画地形水深图的陆地填充
【python海洋专题八】Cartopy画地形水深图的contourf填充间隔数调整
【python海洋专题九】Cartopy画地形等深线图
【python海洋专题十】Cartopy画特定区域的地形等深线图
【python海洋专题十一】colormap调色
全文代码
图片
数据一:
# -*- 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
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
from pylab import *
import seaborn as sns
from matplotlib import cm# ----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)
# -------------# read data------------
a = Dataset('D:\pycharm_work\data\skt.sfc.mon.ltm.nc')
print(a)
lon = a.variables['lon'][:]
lat = a.variables['lat'][:]
time = a.variables['time'][:]
skt = a.variables['skt'][:, :, :]
# 查看每个变量的信息
print(a.variables['lat'])
print(a.variables['lon'])
print(a.variables['time'])
print(a.variables['skt'])
# -------mean skt----------
print(skt.shape)
print(lon.shape)
print(lat)
# skt的时间维度在第一个
skt_mean = np.nanmean(skt, axis=0)
print(skt_mean.shape)
# -------- find scs 's temp-----------
print(np.where(lon >= 100)) # 54
print(np.where(lon >= 123)) # 66
print(np.where(lat >= 0)) # 47
print(np.where(lat >= 25)) # 34
lon1 = lon[53:67]
lat1 = lat[33:48]
skt1 = skt_mean[33:48, 53:67]-273.15
print(skt1)
# --------meshgrid---------
[x, y] = meshgrid(lon1, lat1)
print(x.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, skt1[:, :], levels=np.linspace(15, 35, 50), extend='both', cmap=cmap_r2,transform=ccrs.PlateCarree())
# ------color-bar设置------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=np.linspace(15, 35, 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(color='k', direction='in') # 更改刻度指向为朝内,颜色设置为蓝色
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_1.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1) # 输出地图,并设置边框空白紧密
plt.show()
参考文献
图片
1:「Numpy」解析numpy.mean函数对高维数组求均值-CSDN博客
2:numpy对数组求平均时如何忽略nan值-CSDN博客
3:numpy mean()函数 详解_np.mean-CSDN博客
数据二:代码:
# -*- 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
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
from pylab import *
import seaborn as sns
from matplotlib import cm# ----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)
# -------------# read data------------
a = Dataset('D:\\pycharm_work\\data\\sst.mnmean.nc')
print(a)
lon = a.variables['lon'][:]
lat = a.variables['lat'][:]
time = a.variables['time'][:]
tmp = a.variables['sst'][:, :, :]
# # 查看每个变量的信息
print(a.variables['lat'])
print(a.variables['lon'])
print(a.variables['time'])
print(a.variables['sst'])
# # # -------mean tmp----------
print(tmp.shape)
print(lon.shape)
# # # tmp的时间维度在第一个
tmp_mean = np.nanmean(tmp, axis=0)
print(tmp_mean.shape)
# # # -------- find scs 's temp-----------
print(np.where(lon >= 100)) # 50
print(np.where(lon >= 123)) # 62
print(np.where(lat >= 0)) # 44
print(np.where(lat >= 25)) # 31
lon1 = lon[49:63]
lat1 = lat[30:45]
sst1 = tmp_mean[30:45, 49:63]
print(sst1)
# # --------meshgrid---------
[x, y] = meshgrid(lon1, lat1)
print(x.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, sst1[:, :], levels=np.linspace(20, 30, 70), 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, 6))
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(color='k', direction='in') # 更改刻度指向为朝内,颜色设置为蓝色
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_o2.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1) # 输出地图,并设置边框空白紧密
plt.show()
数据二全球区域的代码:
# -*- 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
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
from pylab import *
import seaborn as sns
from matplotlib import cm# ----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)
# -------------# read data------------
a = Dataset('D:\\pycharm_work\\data\\sst.mnmean.nc')
print(a)
lon = a.variables['lon'][:]
lat = a.variables['lat'][:]
time = a.variables['time'][:]
tmp = a.variables['sst'][:, :, :]
# # 查看每个变量的信息
print(a.variables['lat'])
print(a.variables['lon'])
print(a.variables['time'])
print(a.variables['sst'])
# # # -------mean tmp----------
print(tmp.shape)
print(lon.shape)
# # # tmp的时间维度在第一个
tmp_mean = np.nanmean(tmp, axis=0)
print(tmp_mean.shape)
# # # -------- find scs 's temp-----------
print(np.where(lon >= 100)) # 50
print(np.where(lon >= 123)) # 62
print(np.where(lat >= 0)) # 44
print(np.where(lat >= 25)) # 31
lon1 = lon[49:63]
lat1 = lat[30:45]
sst1 = tmp_mean[30:45, 49:63]
print(sst1)
# # --------meshgrid---------
[x, y] = meshgrid(lon, lat)
print(x.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([0, 360, -90, 90], 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, tmp_mean[:, :], levels=np.linspace(10, 30, 70), extend='both', cmap=cmap_r2,transform=ccrs.PlateCarree())
# ------color-bar设置------------
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical', ticks=np.linspace(10, 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(0, 360, 30), crs=ccrs.PlateCarree()) # 添加经纬度
ax.set_xticklabels(np.arange(0, 360, 30), fontsize=4)
ax.set_yticks(np.arange(-90, 90, 20), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(-90, 90, 20), fontsize=4)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.tick_params(color='k', direction='in') # 更改刻度指向为朝内,颜色设置为蓝色
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False, xlocs=np.arange(-180, 360, 30), ylocs=np.arange(-90, 90, 20),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_o1.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1) # 输出地图,并设置边框空白紧密
plt.show()