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

2023-10-04 13:04

本文主要是介绍【python海洋专题十】Cartopy画特定区域的地形等深线图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

前几期可以认为关于平面的元素画法🆗了

本期关于特定区域平面画法

全球区域水深图

在这里插入图片描述
在这里插入图片描述

本期内容

画某元素特定区域的平面图:我有两个方法:

第一个:裁剪nc文件

第二个:掩盖其他区域,只显示特定区域的平面图。

1:裁剪nc文件

# scs's range is lon from 100 to 123;lat from 0 to 25;
print(np.where(lon >= 100))# 8400
print(np.where(lon >= 123))# 9090
print(np.where(lat >= 0))# 2700
print(np.where(lat >= 25))# 3450
lon1=lon[8400:9090]
lat1=lat[2700:3450]
ele1=ele[2700:3450,8400:9090]

目的找到范围的初始和终止位置。

图片

大区域证明数据的裁剪!

2画全球区域但只显示特定区域

ax.set_extent([100, 123, 0, 25], crs=ccrs.PlateCarree())# 设置显示范围

图片

参考文献及其在本文中的作用

1:Python学习笔记:numpy选择符合条件数据:select、where、choose、nonzero - Hider1214 - 博客园 (cnblogs.com)

全文代码

1全球区域水深图

# -*- 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 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 pylab import *
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_rcmap = Blues_9.mpl_colormap
cmap_r = reverse_colourmap(cmap)
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\etopo2.nc')
print(a)
lon = a.variables['lon'][:]
lat = a.variables['lat'][:]
ele = a.variables['topo'][:,:]
lon1=lon[1:10800:110]
lat1=lat[1:5400:110]
ele1=ele[1:5400:110,1:10800:110]
print(len(lon1))
print(len(lat))
# 图三
# 设置地图全局属性
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设置线宽;linestyle设置线型
cs = ax.contourf(lon1, lat1, ele1, levels=np.arange(-9000,0,20),extend='both',cmap=cmap_r1, transform=ccrs.PlateCarree())
# ------colorbar设置
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical',ticks=np.linspace(-9000, 0, 10))
cb.set_label('depth', fontsize=4, color='k')#设置colorbar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in') #设置colorbar刻度字体大小。
cf = ax.contour(lon, lat, ele[:, :], levels=np.linspace(-9000, 0, 5),colors='gray', linestyles='-',linewidths=0.2,transform=ccrs.PlateCarree())
# 添加标题
ax.set_title('Etopo', 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, 180, 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_elevation03.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()

2:裁剪nc文件;

# -*- 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 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 pylab import *
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_rcmap = Blues_9.mpl_colormap
cmap_r = reverse_colourmap(cmap)
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\etopo2.nc')
print(a)
lon = a.variables['lon'][:]
lat = a.variables['lat'][:]
ele = a.variables['topo'][:]
print(lon)
print(lat)
# scs's range is lon from 100 to 123;lat from 0 to 25;
# so
print(np.where(lon >= 100))# 8400
print(np.where(lon >= 123))# 9090
print(np.where(lat >= 0))# 2700
print(np.where(lat >= 25))# 3450
lon1=lon[8400:9090]
lat1=lat[2700:3450]
ele1=ele[2700:3450,8400:9090]
# 图三
# 设置地图全局属性
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设置线宽;linestyle设置线型
cs = ax.contourf(lon1, lat1, ele1, levels=np.arange(-9000,0,20),extend='both',cmap=cmap_r1, transform=ccrs.PlateCarree())
# ------colorbar设置
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical',ticks=np.linspace(-9000, 0, 10))
cb.set_label('depth', fontsize=4, color='k')#设置colorbar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in') #设置colorbar刻度字体大小。
cf = ax.contour(lon, lat, ele[:, :], levels=[-5000,-2000,-500,-300,-100,-50,-10],colors='gray', linestyles='-',linewidths=0.2,transform=ccrs.PlateCarree())
# 添加标题
ax.set_title('Etopo', 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_elevation1.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()

3:掩盖其他区域,只显示特定区域的平面图。

# -*- 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 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 pylab import *
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_rcmap = Blues_9.mpl_colormap
cmap_r = reverse_colourmap(cmap)
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\etopo2.nc')
print(a)
lon = a.variables['lon'][:]
lat = a.variables['lat'][:]
ele = a.variables['topo'][:,:]
lon1=lon[1:10800:110]
lat1=lat[1:5400:110]
ele1=ele[1:5400:110,1:10800:110]
print(len(lon1))
print(len(lat))
# 图三
# 设置地图全局属性
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设置线宽;linestyle设置线型
cs = ax.contourf(lon1, lat1, ele1, levels=np.arange(-9000,0,20),extend='both',cmap=cmap_r1, transform=ccrs.PlateCarree())
# ------colorbar设置
cb = plt.colorbar(cs, ax=ax, extend='both', orientation='vertical',ticks=np.linspace(-9000, 0, 10))
cb.set_label('depth', fontsize=4, color='k')#设置colorbar的标签字体及其大小
cb.ax.tick_params(labelsize=4, direction='in') #设置colorbar刻度字体大小。
cf = ax.contour(lon, lat, ele[:, :], levels=np.linspace(-9000, 0, 5),colors='gray', linestyles='-',linewidths=0.2,transform=ccrs.PlateCarree())
# 添加标题
ax.set_title('Etopo', fontsize=4)
# 利用Formatter格式化刻度标签
ax.set_xticks(np.arange(100, 123, 5), crs=ccrs.PlateCarree())#添加经纬度
ax.set_xticklabels(np.arange(100, 123, 5), fontsize=4)
ax.set_yticks(np.arange(0, 25, 5), crs=ccrs.PlateCarree())
ax.set_yticklabels(np.arange(0, 25, 5), 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, 5), ylocs=np.arange(0, 25, 5),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_elevation03.jpg', dpi=600, bbox_inches='tight', pad_inches=0.1)  # 输出地图,并设置边框空白紧密
plt.show()

这篇关于【python海洋专题十】Cartopy画特定区域的地形等深线图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/2112

相关文章

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

【专题】2024飞行汽车技术全景报告合集PDF分享(附原数据表)

原文链接: https://tecdat.cn/?p=37628 6月16日,小鹏汇天旅航者X2在北京大兴国际机场临空经济区完成首飞,这也是小鹏汇天的产品在京津冀地区进行的首次飞行。小鹏汇天方面还表示,公司准备量产,并计划今年四季度开启预售小鹏汇天分体式飞行汽车,探索分体式飞行汽车城际通勤。阅读原文,获取专题报告合集全文,解锁文末271份飞行汽车相关行业研究报告。 据悉,业内人士对飞行汽车行业

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

nudepy,一个有趣的 Python 库!

更多资料获取 📚 个人网站:ipengtao.com 大家好,今天为大家分享一个有趣的 Python 库 - nudepy。 Github地址:https://github.com/hhatto/nude.py 在图像处理和计算机视觉应用中,检测图像中的不适当内容(例如裸露图像)是一个重要的任务。nudepy 是一个基于 Python 的库,专门用于检测图像中的不适当内容。该

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip

HTML提交表单给python

python 代码 from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)@app.route('/')def form():# 渲染表单页面return render_template('./index.html')@app.route('/submit_form',

音视频入门基础:WAV专题(10)——FFmpeg源码中计算WAV音频文件每个packet的pts、dts的实现

一、引言 从文章《音视频入门基础:WAV专题(6)——通过FFprobe显示WAV音频文件每个数据包的信息》中我们可以知道,通过FFprobe命令可以打印WAV音频文件每个packet(也称为数据包或多媒体包)的信息,这些信息包含该packet的pts、dts: 打印出来的“pts”实际是AVPacket结构体中的成员变量pts,是以AVStream->time_base为单位的显

Python QT实现A-star寻路算法

目录 1、界面使用方法 2、注意事项 3、补充说明 用Qt5搭建一个图形化测试寻路算法的测试环境。 1、界面使用方法 设定起点: 鼠标左键双击,设定红色的起点。左键双击设定起点,用红色标记。 设定终点: 鼠标右键双击,设定蓝色的终点。右键双击设定终点,用蓝色标记。 设置障碍点: 鼠标左键或者右键按着不放,拖动可以设置黑色的障碍点。按住左键或右键并拖动,设置一系列黑色障碍点