網(wǎng)站轉(zhuǎn)化附子seo教程
python繪制年平均海表溫度、鹽度、ph圖
文章目錄
- python繪制年平均海表溫度、鹽度、ph分布圖
- 前言
- 一、數(shù)據(jù)準(zhǔn)備
- 二、代碼編寫
- 2.1. python繪制年平均海表溫度(主要)
- 2.2. python繪制年平均海表鹽度(選看)
- 2.3. python繪制年平均海表ph(選看)
- 總結(jié)
python繪制年平均海表溫度、鹽度、ph分布圖
所屬目錄:紫菜創(chuàng)建時(shí)間:2025/2/18更新時(shí)間:2025/2/19URL:https://blog.csdn.net/2301_78630677/article/details/145716784
前言
本文主要使用python繪制年平均海表溫度、鹽度、ph分布圖,所用數(shù)據(jù)來源于Bio-ORACLE
參考文章:
Python繪制海表溫度
【python海洋專題十二】年平均的南海海表面溫度圖
所用到的中國(guó)地圖shp文件:
鏈接:https://pan.baidu.com/s/1q9hitI11CCYDWvBTWbAevg
提取碼:9ju8
一、數(shù)據(jù)準(zhǔn)備
在Bio-ORACLE官網(wǎng) 下載所需的 2010-2020平均海表Ocean temperature、Salinity、pH數(shù)據(jù)
點(diǎn)擊前往下載地址
下載下來的環(huán)境數(shù)據(jù)為.nc文件,也就是NetCDF格式。
?NetCDF(Network Common Data Form)格式是一種用于存儲(chǔ)和共享科學(xué)數(shù)據(jù)的標(biāo)準(zhǔn)格式,廣泛應(yīng)用于氣象學(xué)、海洋學(xué)、地球科學(xué)等領(lǐng)域?。.nc文件是NetCDF文件的擴(kuò)展名,主要用于存儲(chǔ)大型科學(xué)和工程數(shù)據(jù)集。
.nc文件的基本結(jié)構(gòu)和特點(diǎn)
?自描述性?:.nc文件包含關(guān)于數(shù)據(jù)集的元數(shù)據(jù),這些元數(shù)據(jù)描述了數(shù)據(jù)集的結(jié)構(gòu)和內(nèi)容,使得用戶無需其他文檔即可理解數(shù)據(jù)。
?可移植性?:.nc文件是二進(jìn)制格式,能夠在不同的平臺(tái)上無縫遷移和使用。
?多維數(shù)組結(jié)構(gòu)?:.nc文件通常包含多個(gè)維度,如時(shí)間、經(jīng)度和緯度,適用于存儲(chǔ)復(fù)雜的多維數(shù)據(jù)集。
補(bǔ)充:
所用的Bio-ORACLE環(huán)境數(shù)據(jù)合集(有需要就下載吧)
Bio-ORACLE數(shù)據(jù)分享[decade 2010-2020] [Surface layers]
二、代碼編寫
接下來主要講述 python繪制年平均海表溫度的代碼,另外兩個(gè)類似,只需要稍加修改
2.1. python繪制年平均海表溫度(主要)
該代碼用于繪制中國(guó)周邊海域的海表溫度(SST)分布圖,并添加了省份邊界、等溫線和網(wǎng)格線等細(xì)節(jié),最后保存pdf文件
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter # 導(dǎo)入經(jīng)緯度格式器
import numpy as np
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature
# 加載NetCDF格式的SST數(shù)據(jù)(替換為你的SST數(shù)據(jù)文件路徑)
ds = xr.open_dataset(r"D:\oceandata\Bio-ORACLE\Temperature [mean].nc") # 假設(shè)你的SST數(shù)據(jù)在該文件中 print(ds.variables) #打印SST數(shù)據(jù)的所有變量名及其相關(guān)信息,通過查看這些信息,你可以確定要使用哪個(gè)變量進(jìn)行繪圖和分析# 選擇SST變量(替換為你的SST變量名)
sst = ds['thetao_mean']# 計(jì)算時(shí)間軸上的平均值(如果時(shí)間是一個(gè)維度)
sst_mean = sst.mean(dim='time') # 假設(shè)'time'是時(shí)間維度 # 創(chuàng)建一個(gè)地圖并設(shè)置投影
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) # 添加陸地和海洋特征
ax.add_feature(cfeature.LAND, color='lightgray')
ax.add_feature(cfeature.OCEAN, color='w', edgecolor='lightgray')
ax.coastlines(color='black')
# 添加省份邊界
shapefile = r"C:\Users\www\Desktop\china_map\china_SHP\省界_Project.shp" # 替換為你的Shapefile文件路徑
china_provinces = ShapelyFeature(Reader(shapefile).geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='none')
ax.add_feature(china_provinces)# 繪制SST平均值數(shù)據(jù)
sst_plot = sst_mean.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), cmap='coolwarm', levels=25, extend='both', add_colorbar=False,vmin=5, vmax=30)
# levels參數(shù)可以調(diào)整等值線的數(shù)量 (具體來說,levels=25 表示將數(shù)據(jù)范圍分成25個(gè)間隔,并繪制出相應(yīng)的等值線。這些等值線將數(shù)據(jù)集的值范圍(在此例中是5到30°C)平均分成25個(gè)部分,每個(gè)部分的上限和下限定義了一條等值線。)# 添加顏色條
cbar = fig.colorbar(sst_plot, drawedges=True, ax=ax, location='right', shrink=0.95, pad=0.08, spacing='uniform', label='Average Sea Surface Temperature (°C)')
cbar.ax.tick_params(labelsize=10) # 設(shè)置色標(biāo)尺標(biāo)簽大小 # 設(shè)置顏色條的刻度標(biāo)簽
cbar.set_ticks(np.arange(5, 31, 5))# 添加等溫線
sst_contour = sst_mean.plot.contour(ax=ax, transform=ccrs.PlateCarree(), colors='gray', levels=130,linewidths=0.5) # levels參數(shù)可以調(diào)整等溫線的數(shù)量 # 為等值線添加標(biāo)簽
plt.clabel(sst_contour, inline=True, fontsize=10, fmt='%1.1f') # 設(shè)置地圖的經(jīng)緯度范圍(可選)
ax.set_extent([110, 135, 20, 40], crs=ccrs.PlateCarree()) # 添加網(wǎng)格線
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, xlocs=np.arange(110, 135, 5), ylocs=np.arange(20, 40, 5),linewidth=0.5, linestyle='--', color='k', alpha=0.8) # 添加網(wǎng)格線
gl.xlabels_top = False
gl.ylabels_right = False
gl.xformatter = LongitudeFormatter() # 使用默認(rèn)的經(jīng)度格式器
gl.yformatter = LatitudeFormatter() # 使用默認(rèn)的緯度格式器
gl.xlabel_style = {'size': 10, 'color': 'black'}
gl.ylabel_style = {'size': 10, 'color': 'black'}
print("Map created successfully!")
# 保存地圖為PDF文件
plt.savefig('scs_sst_1.pdf', dpi=600, bbox_inches='tight', pad_inches=0.1)
# 顯示地圖
plt.show()
代碼大概包括以下流程:
- 加載數(shù)據(jù):讀取 NetCDF 文件并提取 SST 變量。
- 數(shù)據(jù)處理:對(duì)時(shí)間維度取平均。
- 創(chuàng)建地圖:設(shè)置投影、添加陸地和海洋特征、繪制省份邊界。
- 繪制 SST 數(shù)據(jù):繪制填充等溫線和等溫線,添加顏色條和標(biāo)簽。
- 設(shè)置地圖范圍與網(wǎng)格線:調(diào)整地圖范圍,添加網(wǎng)格線并格式化標(biāo)簽。
- 保存與顯示:保存地圖為 PDF 文件并顯示。
print(ds.variables) #打印SST數(shù)據(jù)的所有變量名及其相關(guān)信息,通過查看這些信息,你可以確定要使用哪個(gè)變量進(jìn)行繪圖和分析
例如該SST數(shù)據(jù)包括四個(gè)變量:time、latitude、longitude、thetao_mean, 其中thetao_mean就是SST變量名。
結(jié)果顯示
2.2. python繪制年平均海表鹽度(選看)
以下代碼與年平均海表溫度的代碼類似(一些注釋信息就沒改過來了,知道意思即可)
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter # 導(dǎo)入經(jīng)緯度格式器
import numpy as np
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature
# 加載NetCDF格式的SST數(shù)據(jù)(替換為你的數(shù)據(jù)文件路徑) ds = xr.open_dataset(r"D:\oceandata\so_baseline_2000_2019_depthsurf_49ed_5fc4_602c_U1739344920620_yandu.nc") # 假設(shè)你的SST數(shù)據(jù)在該文件中 print(ds.variables)
# 選擇SST變量(替換為你的SST變量名)
sst = ds['so_mean']# 計(jì)算時(shí)間軸上的平均值(如果時(shí)間是一個(gè)維度)
sst_mean = sst.mean(dim='time') # 假設(shè)'time'是時(shí)間維度 # 創(chuàng)建一個(gè)地圖并設(shè)置投影
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) # 添加陸地和海洋特征
ax.add_feature(cfeature.LAND, color='lightgray')
ax.add_feature(cfeature.OCEAN, color='w', edgecolor='lightgray')
ax.coastlines(color='black')
# 添加省份邊界
shapefile = r"C:\Users\www\Desktop\a5bc0-main\china_SHP\省界_Project.shp" # 替換為你的Shapefile文件路徑
china_provinces = ShapelyFeature(Reader(shapefile).geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='none')
ax.add_feature(china_provinces)# 繪制SST平均值數(shù)據(jù)
sst_plot = sst_mean.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), cmap='coolwarm', levels=15, extend='both', add_colorbar=False,vmin=20, vmax=35) # levels參數(shù)可以調(diào)整等溫線的數(shù)量 # 添加顏色條
cbar = fig.colorbar(sst_plot, drawedges=True, ax=ax, location='right', shrink=0.95, pad=0.08, spacing='uniform', label='Average Sea Surface Salinity (psu)')
cbar.ax.tick_params(labelsize=10) # 設(shè)置色標(biāo)尺標(biāo)簽大小 # 設(shè)置顏色條的刻度標(biāo)簽
cbar.set_ticks(np.arange(20, 36, 3))# 添加等溫線
sst_contour = sst_mean.plot.contour(ax=ax, transform=ccrs.PlateCarree(), colors='gray', levels=50,linewidths=0.5) # 為等值線添加標(biāo)簽
plt.clabel(sst_contour, inline=True, fontsize=10, fmt='%1.1f') # 設(shè)置地圖的經(jīng)緯度范圍(可選)
ax.set_extent([110, 135, 20, 40], crs=ccrs.PlateCarree()) # 添加網(wǎng)格線
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, xlocs=np.arange(110, 135, 5), ylocs=np.arange(20, 40, 5),linewidth=0.5, linestyle='--', color='k', alpha=0.8) # 添加網(wǎng)格線
gl.xlabels_top = False
gl.ylabels_right = False
gl.xformatter = LongitudeFormatter() # 使用默認(rèn)的經(jīng)度格式器
gl.yformatter = LatitudeFormatter() # 使用默認(rèn)的緯度格式器
gl.xlabel_style = {'size': 10, 'color': 'black'}
gl.ylabel_style = {'size': 10, 'color': 'black'}
print("Map created successfully!")# 保存地圖為PDF文件
plt.savefig('scs_yandu_1.pdf', dpi=600, bbox_inches='tight', pad_inches=0.1)
# 顯示地圖
plt.show()
2.3. python繪制年平均海表ph(選看)
以下代碼與年平均海表溫度的代碼類似,只不過因?yàn)閜h的值較小,我們可以先計(jì)算一下數(shù)據(jù)中的最大值與最小值,方便確定ph大小
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter # 導(dǎo)入經(jīng)緯度格式器
import numpy as np
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature
# 加載NetCDF格式的SST數(shù)據(jù)(替換為你的SST數(shù)據(jù)文件路徑) ds = xr.open_dataset(r"D:\oceandata\ph_baseline_2000_2018_depthsurf_f606_6dc8_6180_U1739344995788_ph.nc") # 假設(shè)你的SST數(shù)據(jù)在'sst.nc'文件中 # 選擇pH變量(替換為你的pH變量名)
ph = ds['ph_mean']# 計(jì)算pH數(shù)據(jù)的最高和最低值
ph_max = ph.max(dim=['time', 'latitude', 'longitude'])
ph_min = ph.min(dim=['time', 'latitude', 'longitude'])print("Maximum pH value:", ph_max)
print("Minimum pH value:", ph_min)print(ds.variables)
# 選擇SST變量(替換為你的SST變量名)
sst = ds['ph_mean']# 計(jì)算時(shí)間軸上的平均值(如果時(shí)間是一個(gè)維度)
sst_mean = sst.mean(dim='time') # 假設(shè)'time'是時(shí)間維度 # 創(chuàng)建一個(gè)地圖并設(shè)置投影
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) # 添加陸地和海洋特征
ax.add_feature(cfeature.LAND, color='lightgray')
ax.add_feature(cfeature.OCEAN, color='w', edgecolor='lightgray')
ax.coastlines(color='black')
# 添加省份邊界
shapefile = r"C:\Users\王浩天\Desktop\a5bc0-main\china_SHP\省界_Project.shp" # 替換為你的Shapefile文件路徑
china_provinces = ShapelyFeature(Reader(shapefile).geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='none')
ax.add_feature(china_provinces)# 繪制SST平均值數(shù)據(jù)
sst_plot = sst_mean.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), cmap='coolwarm', levels=15, extend='both', add_colorbar=False,vmin=8, vmax=8.2) # levels參數(shù)可以調(diào)整等溫線的數(shù)量 # 添加顏色條
cbar = fig.colorbar(sst_plot, drawedges=True, ax=ax, location='right', shrink=0.95, pad=0.08, spacing='uniform', label='Average Sea Surface pH')
cbar.ax.tick_params(labelsize=10) # 設(shè)置色標(biāo)尺標(biāo)簽大小 # 設(shè)置顏色條的刻度標(biāo)簽
cbar.set_ticks(np.arange(8, 8.25, 0.05))# 添加等溫線
sst_contour = sst_mean.plot.contour(ax=ax, transform=ccrs.PlateCarree(), colors='gray', levels=200,linewidths=0.5) # 為等值線添加標(biāo)簽
plt.clabel(sst_contour, inline=True, fontsize=10, fmt='%1.3f') #保留小數(shù)點(diǎn)后三位# 設(shè)置地圖的經(jīng)緯度范圍(可選)
ax.set_extent([110, 135, 20, 40], crs=ccrs.PlateCarree()) # 添加網(wǎng)格線
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, xlocs=np.arange(110, 135, 5), ylocs=np.arange(20, 40, 5),linewidth=0.5, linestyle='--', color='k', alpha=0.8) # 添加網(wǎng)格線
gl.xlabels_top = False
gl.ylabels_right = False
gl.xformatter = LongitudeFormatter() # 使用默認(rèn)的經(jīng)度格式器
gl.yformatter = LatitudeFormatter() # 使用默認(rèn)的緯度格式器
gl.xlabel_style = {'size': 10, 'color': 'black'}
gl.ylabel_style = {'size': 10, 'color': 'black'}
print("Map created successfully!")
# 保存地圖為PDF文件
plt.savefig('scs_ph_1.pdf', dpi=600, bbox_inches='tight', pad_inches=0.1)
# 顯示地圖
plt.show()
總結(jié)
主要是以繪制年平均海表溫度分布圖為例,其余環(huán)境數(shù)據(jù)也類似。
2025/2/19