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中使用第三方库xlutils来追加写入Excel文件示例
Apr 05 Python
Python实现数通设备端口使用情况监控实例
Jul 15 Python
深入理解Python3中的http.client模块
Mar 29 Python
python查询mysql,返回json的实例
Mar 26 Python
Python使用min、max函数查找二维数据矩阵中最小、最大值的方法
May 15 Python
python设定并获取socket超时时间的方法
Jan 12 Python
对python过滤器和lambda函数的用法详解
Jan 21 Python
python使用OpenCV模块实现图像的融合示例代码
Apr 10 Python
在python中求分布函数相关的包实例
Apr 15 Python
Python virtualenv虚拟环境实现过程解析
Apr 18 Python
详解pandas获取Dataframe元素值的几种方法
Jun 14 Python
Python 读写 Matlab Mat 格式数据的操作
May 19 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
为php4加入动态flash文件的生成的支持
2006/10/09 PHP
如何写php守护进程(Daemon)
2015/12/30 PHP
PHP5.5迭代生成器用法实例详解
2016/03/16 PHP
PHP数组去重的更快实现方式分析
2018/05/09 PHP
PHP连接及操作PostgreSQL数据库的方法详解
2019/01/30 PHP
Laravel 5.5 异常处理 & 错误日志的解决
2019/10/17 PHP
Laravel 微信小程序后端搭建步骤详解
2019/11/26 PHP
关于viewport,Ext.panel和Ext.form.panel的关系
2009/05/07 Javascript
根据对象的某一属性进行排序的js代码(如:name,age)
2010/08/10 Javascript
Javascript的各种节点操作实例演示代码
2012/06/27 Javascript
xmlhttp缓存清除的2种解决方法
2013/12/13 Javascript
简单的邮箱登陆的提示效果类似于yahoo邮箱
2014/02/26 Javascript
js 判断控件获得焦点的示例代码
2014/03/04 Javascript
javascript获取checkbox复选框获取选中的选项
2014/08/12 Javascript
jQuery插件扩展测试实例
2016/06/21 Javascript
AngularJS中的按需加载ocLazyLoad示例
2017/01/11 Javascript
Vuex之理解Getters的用法实例
2017/04/19 Javascript
Node.js+jade+mongodb+mongoose实现爬虫分离入库与生成静态文件的方法
2017/09/20 Javascript
jQuery实现点击自身以外区域关闭弹出层功能完整示例【改进版】
2018/07/31 jQuery
vue 自动化路由实现代码
2019/09/03 Javascript
在Python的struct模块中进行数据格式转换的方法
2015/06/17 Python
Python计算开方、立方、圆周率,精确到小数点后任意位的方法
2018/07/17 Python
基于Python函数和变量名解析
2019/07/19 Python
python plotly绘制直方图实例详解
2019/07/22 Python
python飞机大战pygame游戏之敌机出场实现方法详解
2019/12/17 Python
TensorFlow使用Graph的基本操作的实现
2020/04/22 Python
Python如何读取、写入CSV数据
2020/07/28 Python
The Hut英国:英国领先的豪华在线百货商店
2019/07/26 全球购物
仓管员岗位职责范文
2013/11/08 职场文书
大学四年个人的自我评价
2014/02/26 职场文书
岗位职责说明书
2014/05/07 职场文书
青奥会口号
2014/06/12 职场文书
办公室主任四风问题对照检查材料思想汇报
2014/09/28 职场文书
党员个人对照检查材料
2014/10/01 职场文书
2016年春季运动会通讯稿
2015/11/25 职场文书
再也不用花钱买漫画!Python爬取某漫画的脚本及源码
2021/06/09 Python