前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Python可视化 | CMA热带气旋最佳路径数据集读取与绘制

Python可视化 | CMA热带气旋最佳路径数据集读取与绘制

作者头像
郭好奇同学
发布于 2021-05-28 08:42:27
发布于 2021-05-28 08:42:27
2.6K00
代码可运行
举报
文章被收录于专栏:好奇心Log好奇心Log
运行总次数:0
代码可运行

点击下方公众号,回复资料,收获惊喜

以前在简书分享过一个路径绘制的方法,然而对于更多情况的路径绘制来说(比如台风路径),每次的路径长度都是不一致的,同时也需要从一个数据文件里很复杂的读取。这次分享一个可以方便读取CMA热带气旋最佳路径数据集的方法。

首先展示该数据集的结构:

不难发现每次tc的路径长度均是不一致的。那么我们要做的就是,给出一个tc的id,读取该tc的路径信息。以下自定义函数便可实现该功能。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import os
import pandas as pd
import numpy as np
from pathlib import Path
from typing import List
from typing import Union
from typing import Tuple
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
def reader(
    typhoon_txt: os.PathLike, code: Union[str, int]
) -> Tuple[List[str], pd.DataFrame]:
    typhoon_txt = Path(typhoon_txt)
if isinstance(code, int):
        code = "{:04}".format(code)
with open(typhoon_txt, "r") as txt_handle:
while True:
            header = txt_handle.readline().split()
if not header:
raise ValueError(f"没有在文件里找到编号为{code}的台风")
if header[4].strip() == code:
break
            [txt_handle.readline() for _ in range(int(header[2]))]
        data_path = pd.read_table(
            txt_handle,
            sep=r"\s+",
            header=None,
            names=["TIME", "I", "LAT", "LONG", "PRES", "WND", "OWD"],
            nrows=int(header[2]),
            dtype={
"I": np.int,
"LAT": np.float32,
"LONG": np.float32,
"PRES": np.float32,
"WND": np.float32,
"OWD": np.float32,
            },
            parse_dates=True,
            date_parser=lambda x: pd.to_datetime(x, format=f"%Y%m%d%H"),
            index_col="TIME",
        )
        data_path["LAT"] = data_path["LAT"] / 10
        data_path["LONG"] = data_path["LONG"] / 10
return header, data_path

比如说,我们读取2006年的08号tc的相关信息:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
head, dat = reader(r"./CH2006BST.txt",'0608')
lat = dat.LAT
lon = dat.LONG
level = dat.I
pressure = dat.PRES

绘图:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#创建Figure
fig = plt.figure(figsize=(15, 12))
#绘制台风路径
ax1 = fig.add_subplot(1,2,1, projection=ccrs.PlateCarree())
#设置ax1的范围
ax1.set_extent([100,160,-10,40])
#为ax1添加海岸线和陆地
ax1.coastlines()
ax1.add_feature(cfeature.LAND) #添加大陆特征
#为ax1添加地理经纬度标签及刻度
ax1.set_xticks(np.arange(100,170,10), crs=ccrs.PlateCarree())
ax1.set_yticks(np.arange(-10,50,10), crs=ccrs.PlateCarree())
ax1.xaxis.set_major_formatter(cticker.LongitudeFormatter())
ax1.yaxis.set_major_formatter(cticker.LatitudeFormatter())
#将绘制台风路径,并将逐六小时坐标点及其对应的台风强度标记
ax1.plot(lon,lat,linewidth=2)
s1 = ax1.scatter(lon,lat,c=pressure,s=(level+1)*13,cmap='Reds_r',vmax=1050,vmin=900,alpha=1)
fig.colorbar(s1,ax=ax1,fraction=0.04)
#绘制台风路径
ax2 = fig.add_subplot(1,2,2, projection=ccrs.PlateCarree())
#设置ax2的范围
ax2.set_extent([100,160,-10,40])
#为ax1添加海岸线
ax2.coastlines()
ax2.add_feature(cfeature.LAND) #添加大陆特征
#为ax2添加地理经纬度标签及刻度
ax2.set_xticks(np.arange(100,170,10), crs=ccrs.PlateCarree())
ax2.set_yticks(np.arange(-10,50,10), crs=ccrs.PlateCarree())
ax2.xaxis.set_major_formatter(cticker.LongitudeFormatter())
ax2.yaxis.set_major_formatter(cticker.LatitudeFormatter())
#将经纬度数据点存入同一数组
points = np.array([lon, lat]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
#设置色标的标准化范围(即将Z维度的数据对应为颜色数组)
norm = plt.Normalize(0, 80)
#设置颜色线条
lc = LineCollection(segments, cmap='jet', norm=norm,transform=ccrs.PlateCarree())        
lc.set_array(dat.WND[:-1])
#绘制线条
line = ax2.add_collection(lc)    
fig.colorbar(lc,ax=ax2,fraction=0.04)
plt.show()

输出图形:

对于左图来说,点大小对应台风等级,点颜色对应台风中心气压,对于有图来说,颜色对应风速大小。

本众号内回复CMA数据可获得本文测试数据。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-05-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 好奇心Log 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
💥开发者 MCP广场重磅上线!
精选全网热门MCP server,让你的AI更好用 🚀
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档