Python绘图实现台风路径可视化代码实例


Posted in Python onOctober 23, 2020

台风是重大灾害性天气,台风引起的直接灾害通常由三方面造成,狂风、暴雨、风暴潮,除此以外台风的这些灾害极易诱发城市内涝、房屋倒塌、山洪、泥石流等次生灾害。正因如此,台风在科研和业务工作中是研究的重点。希望这次台风路径可视化可以给予大家一点点帮助。

台风路径的获取

中国气象局(CMA)

中国气象局(CMA)的台风最佳路径数据集(BST),BST是之后对历史台风路径进行校正后发布的,其经纬度、强度、气压具有更高的可靠性,但是时间分辨率为6小时,部分3小时,这一点不如观测数据。下载地址:

http://tcdata.typhoon.org.cn/

温州台风网

温州台风网的数据是实时发布数据的记录,时间分辨率最高达1小时,对于台风轨迹具有更加精细化的表述。下载地址:

http://www.wztf121.com/

示例

导入模块并读取数据,使用BST的2018年台风路径数据作为示例,已经将原始的txt文件转换为xls文件。

import os, glob
import pandas as pd
import numpy as np
import shapely.geometry as sgeom
import matplotlib.pyplot as plt
from matplotlib.image import imread
from matplotlib.animation import FuncAnimation
import matplotlib.lines as mlines
import cartopy.crs as ccrs
import cartopy.feature as cfeat
from cartopy.mpl.ticker import LongitudeFormatter,LatitudeFormatter
import cartopy.io.shapereader as shpreader
import cartopy.io.img_tiles as cimgt
from PIL import Image
import warnings 
warnings.filterwarnings('ignore')
df = pd.read_csv('./2018typhoon.csv')

定义等级色标

def get_color(level):
  global color
  if level == '热带低压' or level == '热带扰动':
    color='#FFFF00'
  elif level == '热带风暴':
    color='#6495ED'
  elif level == '强热带风暴':
    color='#3CB371'
  elif level == '台风':
    color='#FFA500'
  elif level == '强台风':
    color='#FF00FF'
  elif level == '超强台风':
    color='#DC143C'
  return color

定义底图函数

def create_map(title, extent):
  fig = plt.figure(figsize=(12, 8))
  ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
  url = 'http://map1c.vis.earthdata.nasa.gov/wmts-geo/wmts.cgi'
  layer = 'BlueMarble_ShadedRelief'
  ax.add_wmts(url, layer)
  ax.set_extent(extent,crs=ccrs.PlateCarree())

  gl = ax.gridlines(draw_labels=False, linewidth=1, color='k', alpha=0.5, linestyle='--')
  gl.xlabels_top = gl.ylabels_right = False 
  ax.set_xticks(np.arange(extent[0], extent[1]+5, 5))
  ax.set_yticks(np.arange(extent[2], extent[3]+5, 5))
  ax.xaxis.set_major_formatter(LongitudeFormatter())
  ax.xaxis.set_minor_locator(plt.MultipleLocator(1))
  ax.yaxis.set_major_formatter(LatitudeFormatter())
  ax.yaxis.set_minor_locator(plt.MultipleLocator(1))
  ax.tick_params(axis='both', labelsize=10, direction='out')

  a = mlines.Line2D([],[],color='#FFFF00',marker='o',markersize=7, label='TD',ls='')
  b = mlines.Line2D([],[],color='#6495ED', marker='o',markersize=7, label='TS',ls='')
  c = mlines.Line2D([],[],color='#3CB371', marker='o',markersize=7, label='STS',ls='')
  d = mlines.Line2D([],[],color='#FFA500', marker='o',markersize=7, label='TY',ls='')
  e = mlines.Line2D([],[],color='#FF00FF', marker='o',markersize=7, label='STY',ls='')
  f = mlines.Line2D([],[],color='#DC143C', marker='o',markersize=7, label='SSTY',ls='')
  ax.legend(handles=[a,b,c,d,e,f], numpoints=1, handletextpad=0, loc='upper left', shadow=True)
  plt.title(f'{title} Typhoon Track', fontsize=15)
  return ax

定义绘制单个台风路径方法,并绘制2018年第18号台风温比亚。

def draw_single(df):
  ax = create_map(df['名字'].iloc[0], [110, 135, 20, 45])
  for i in range(len(df)):
    ax.scatter(list(df['经度'])[i], list(df['纬度'])[i], marker='o', s=20, color=get_color(list(df['强度'])[i]))

  for i in range(len(df)-1):
    pointA = list(df['经度'])[i],list(df['纬度'])[i]
    pointB = list(df['经度'])[i+1],list(df['纬度'])[i+1]
    ax.add_geometries([sgeom.LineString([pointA, pointB])], color=get_color(list(df['强度'])[i+1]),crs=ccrs.PlateCarree())
  plt.savefig('./typhoon_one.png')
draw_single(df[df['编号']==1818])

Python绘图实现台风路径可视化代码实例

定义绘制多个台风路径方法,并绘制2018年全年的全部台风路径。

def draw_multi(df):
  L = list(set(df['编号']))
  L.sort(key=list(df['编号']).index)
  ax = create_map('2018', [100, 180, 0, 45])
  for number in L:
    df1 = df[df['编号']==number]
    for i in range(len(df1)-1):
      pointA = list(df1['经度'])[i],list(df1['纬度'])[i]
      pointB = list(df1['经度'])[i+1],list(df1['纬度'])[i+1]
      ax.add_geometries([sgeom.LineString([pointA, pointB])], color=get_color(list(df1['强度'])[i+1]),crs=ccrs.PlateCarree())
  plt.savefig('./typhoon_multi.png')
draw_multi(df)

Python绘图实现台风路径可视化代码实例

定义绘制单个台风gif路径演变方法,并绘制2018年第18号台风的gif路径图。

def draw_single_gif(df):
  for state in range(len(df.index))[:]:
    ax = create_map(f'{df["名字"].iloc[0]} {df["时间"].iloc[state]}', [110, 135, 20, 45])
    for i in range(len(df[:state])):
      ax.scatter(df['经度'].iloc[i], df['纬度'].iloc[i], marker='o', s=20, color=get_color(df['强度'].iloc[i]))
    for i in range(len(df[:state])-1):
      pointA = df['经度'].iloc[i],df['纬度'].iloc[i]
      pointB = df['经度'].iloc[i+1],df['纬度'].iloc[i+1]
      ax.add_geometries([sgeom.LineString([pointA, pointB])], color=get_color(df['强度'].iloc[i+1]),crs=ccrs.PlateCarree())
    print(f'正在绘制第{state}张轨迹图')
    plt.savefig(f'./{df["名字"].iloc[0]}{str(state).zfill(3)}.png', bbox_inches='tight')
  # 将图片拼接成动画
  imgFiles = list(glob.glob(f'./{df["名字"].iloc[0]}*.png'))
  images = [Image.open(fn) for fn in imgFiles]
  im = images[0]
  filename = f'./track_{df["名字"].iloc[0]}.gif'
  im.save(fp=filename, format='gif', save_all=True, append_images=images[1:], duration=500)
draw_single_gif(df[df['编号']==1818])

Python绘图实现台风路径可视化代码实例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python 运算符 供重载参考
Jun 11 Python
使用Python3编写抓取网页和只抓网页图片的脚本
Aug 20 Python
python3.5 + PyQt5 +Eric6 实现的一个计算器代码
Mar 11 Python
ubuntu17.4下为python和python3装上pip的方法
Jun 12 Python
Python版名片管理系统
Nov 30 Python
Python 实现王者荣耀中的敏感词过滤示例
Jan 21 Python
Python 正则表达式爬虫使用案例解析
Sep 23 Python
Python 读取 YUV(NV12) 视频文件实例
Dec 09 Python
Python中三维坐标空间绘制的实现
Sep 22 Python
Numpy中np.random.rand()和np.random.randn() 用法和区别详解
Oct 23 Python
pymongo insert_many 批量插入的实例
Dec 05 Python
总结python多进程multiprocessing的相关知识
Jun 29 Python
Python实现JS解密并爬取某音漫客网站
Oct 23 #Python
解决Python 写文件报错TypeError的问题
Oct 23 #Python
python 利用Pyinstaller打包Web项目
Oct 23 #Python
python logging模块的使用详解
Oct 23 #Python
Pycharm自动添加文件头注释和函数注释参数的方法
Oct 23 #Python
Python中免验证跳转到内容页的实例代码
Oct 23 #Python
python对 MySQL 数据库进行增删改查的脚本
Oct 22 #Python
You might like
PHP5中MVC结构学习
2006/10/09 PHP
PHP调用.NET的WebService 简单实例
2015/03/27 PHP
php函数mkdir实现递归创建层级目录
2016/10/27 PHP
thinkphp3.2中实现phpexcel导出带生成图片示例
2017/02/14 PHP
jquery按回车提交数据的代码示例
2013/11/05 Javascript
JS返回iframe中frameBorder属性值的方法
2015/04/01 Javascript
jQuery模拟原生态App上拉刷新下拉加载更多页面及原理
2015/08/10 Javascript
js如何改变文章的字体大小
2016/01/08 Javascript
解析Node.js异常处理中domain模块的使用方法
2016/02/16 Javascript
如何使用AngularJs打造权限管理系统【简易型】
2016/05/09 Javascript
Bootstrap 手风琴菜单的实现代码
2017/01/20 Javascript
在 Angular2 中实现自定义校验指令(确认密码)的方法
2017/01/23 Javascript
详解nodeJs文件系统(fs)与流(stream)
2018/01/24 NodeJs
vue.js给动态绑定的radio列表做批量编辑的方法
2018/02/28 Javascript
vue 设置路由的登录权限的方法
2018/07/03 Javascript
优雅地使用loading(推荐)
2019/04/20 Javascript
jquery检测上传文件大小示例
2020/04/26 jQuery
[01:02:53]DOTA2上海特级锦标赛主赛事日 - 5 总决赛Liquid VS Secret第二局
2016/03/06 DOTA
[55:48]VGJ.S vs TNC Supermajor 败者组 BO3 第二场 6.6
2018/06/07 DOTA
Python兔子毒药问题实例分析
2015/03/05 Python
python中星号变量的几种特殊用法
2016/09/07 Python
python实现TF-IDF算法解析
2018/01/02 Python
多个应用共存的Django配置方法
2018/05/30 Python
详解Python logging调用Logger.info方法的处理过程
2019/02/12 Python
利用Python实现手机短信监控通知的方法
2019/07/22 Python
Python中利用LSTM模型进行时间序列预测分析的实现
2019/07/26 Python
利用python实现短信和电话提醒功能的例子
2019/08/08 Python
关于Python解包知识点总结
2020/05/05 Python
零基础学Python之前需要学c语言吗
2020/07/21 Python
Pytorch 中的optimizer使用说明
2021/03/03 Python
Lookfantastic日本官网:英国知名护肤、化妆品和头发护理购物网站
2018/04/21 全球购物
给水工程专业毕业生自荐信
2014/01/28 职场文书
大学生自我评价范文分享
2014/02/21 职场文书
民族团结先进集体事迹材料
2014/05/22 职场文书
2015年妇联工作总结范文
2015/04/22 职场文书
mysql拆分字符串作为查询条件的示例代码
2022/07/07 MySQL