網(wǎng)站轉化附子seo教程
python繪制年平均海表溫度、鹽度、ph圖
文章目錄
- python繪制年平均海表溫度、鹽度、ph分布圖
- 前言
- 一、數(shù)據(jù)準備
- 二、代碼編寫
- 2.1. python繪制年平均海表溫度(主要)
- 2.2. python繪制年平均海表鹽度(選看)
- 2.3. python繪制年平均海表ph(選看)
- 總結
python繪制年平均海表溫度、鹽度、ph分布圖
所屬目錄:紫菜創(chuàng)建時間:2025/2/18更新時間:2025/2/19URL:https://blog.csdn.net/2301_78630677/article/details/145716784
前言
本文主要使用python繪制年平均海表溫度、鹽度、ph分布圖,所用數(shù)據(jù)來源于Bio-ORACLE
參考文章:
Python繪制海表溫度
【python海洋專題十二】年平均的南海海表面溫度圖
所用到的中國地圖shp文件:
鏈接:https://pan.baidu.com/s/1q9hitI11CCYDWvBTWbAevg
提取碼:9ju8
一、數(shù)據(jù)準備
在Bio-ORACLE官網(wǎng) 下載所需的 2010-2020平均海表Ocean temperature、Salinity、pH數(shù)據(jù)
點擊前往下載地址
下載下來的環(huán)境數(shù)據(jù)為.nc文件,也就是NetCDF格式。
?NetCDF(Network Common Data Form)格式是一種用于存儲和共享科學數(shù)據(jù)的標準格式,廣泛應用于氣象學、海洋學、地球科學等領域?。.nc文件是NetCDF文件的擴展名,主要用于存儲大型科學和工程數(shù)據(jù)集。
.nc文件的基本結構和特點
?自描述性?:.nc文件包含關于數(shù)據(jù)集的元數(shù)據(jù),這些元數(shù)據(jù)描述了數(shù)據(jù)集的結構和內容,使得用戶無需其他文檔即可理解數(shù)據(jù)。
?可移植性?:.nc文件是二進制格式,能夠在不同的平臺上無縫遷移和使用。
?多維數(shù)組結構?:.nc文件通常包含多個維度,如時間、經度和緯度,適用于存儲復雜的多維數(shù)據(jù)集。
補充:
所用的Bio-ORACLE環(huán)境數(shù)據(jù)合集(有需要就下載吧)
Bio-ORACLE數(shù)據(jù)分享[decade 2010-2020] [Surface layers]
二、代碼編寫
接下來主要講述 python繪制年平均海表溫度的代碼,另外兩個類似,只需要稍加修改
2.1. python繪制年平均海表溫度(主要)
該代碼用于繪制中國周邊海域的海表溫度(SST)分布圖,并添加了省份邊界、等溫線和網(wǎng)格線等細節(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 # 導入經緯度格式器
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") # 假設你的SST數(shù)據(jù)在該文件中 print(ds.variables) #打印SST數(shù)據(jù)的所有變量名及其相關信息,通過查看這些信息,你可以確定要使用哪個變量進行繪圖和分析# 選擇SST變量(替換為你的SST變量名)
sst = ds['thetao_mean']# 計算時間軸上的平均值(如果時間是一個維度)
sst_mean = sst.mean(dim='time') # 假設'time'是時間維度 # 創(chuàng)建一個地圖并設置投影
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ù)可以調整等值線的數(shù)量 (具體來說,levels=25 表示將數(shù)據(jù)范圍分成25個間隔,并繪制出相應的等值線。這些等值線將數(shù)據(jù)集的值范圍(在此例中是5到30°C)平均分成25個部分,每個部分的上限和下限定義了一條等值線。)# 添加顏色條
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) # 設置色標尺標簽大小 # 設置顏色條的刻度標簽
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ù)可以調整等溫線的數(shù)量 # 為等值線添加標簽
plt.clabel(sst_contour, inline=True, fontsize=10, fmt='%1.1f') # 設置地圖的經緯度范圍(可選)
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() # 使用默認的經度格式器
gl.yformatter = LatitudeFormatter() # 使用默認的緯度格式器
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ù)處理:對時間維度取平均。
- 創(chuàng)建地圖:設置投影、添加陸地和海洋特征、繪制省份邊界。
- 繪制 SST 數(shù)據(jù):繪制填充等溫線和等溫線,添加顏色條和標簽。
- 設置地圖范圍與網(wǎng)格線:調整地圖范圍,添加網(wǎng)格線并格式化標簽。
- 保存與顯示:保存地圖為 PDF 文件并顯示。
print(ds.variables) #打印SST數(shù)據(jù)的所有變量名及其相關信息,通過查看這些信息,你可以確定要使用哪個變量進行繪圖和分析
例如該SST數(shù)據(jù)包括四個變量:time、latitude、longitude、thetao_mean, 其中thetao_mean就是SST變量名。
結果顯示
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 # 導入經緯度格式器
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") # 假設你的SST數(shù)據(jù)在該文件中 print(ds.variables)
# 選擇SST變量(替換為你的SST變量名)
sst = ds['so_mean']# 計算時間軸上的平均值(如果時間是一個維度)
sst_mean = sst.mean(dim='time') # 假設'time'是時間維度 # 創(chuàng)建一個地圖并設置投影
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ù)可以調整等溫線的數(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) # 設置色標尺標簽大小 # 設置顏色條的刻度標簽
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) # 為等值線添加標簽
plt.clabel(sst_contour, inline=True, fontsize=10, fmt='%1.1f') # 設置地圖的經緯度范圍(可選)
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() # 使用默認的經度格式器
gl.yformatter = LatitudeFormatter() # 使用默認的緯度格式器
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(選看)
以下代碼與年平均海表溫度的代碼類似,只不過因為ph的值較小,我們可以先計算一下數(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 # 導入經緯度格式器
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") # 假設你的SST數(shù)據(jù)在'sst.nc'文件中 # 選擇pH變量(替換為你的pH變量名)
ph = ds['ph_mean']# 計算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']# 計算時間軸上的平均值(如果時間是一個維度)
sst_mean = sst.mean(dim='time') # 假設'time'是時間維度 # 創(chuàng)建一個地圖并設置投影
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ù)可以調整等溫線的數(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) # 設置色標尺標簽大小 # 設置顏色條的刻度標簽
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) # 為等值線添加標簽
plt.clabel(sst_contour, inline=True, fontsize=10, fmt='%1.3f') #保留小數(shù)點后三位# 設置地圖的經緯度范圍(可選)
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() # 使用默認的經度格式器
gl.yformatter = LatitudeFormatter() # 使用默認的緯度格式器
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()
總結
主要是以繪制年平均海表溫度分布圖為例,其余環(huán)境數(shù)據(jù)也類似。
2025/2/19