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-基础-入门 简介
Aug 09 Python
Python实现二分法算法实例
Feb 02 Python
Python中list初始化方法示例
Sep 18 Python
Python 逐行分割大txt文件的方法
Oct 10 Python
运动检测ViBe算法python实现代码
Jan 09 Python
用十张图详解TensorFlow数据读取机制(附代码)
Feb 06 Python
python实现AES加密和解密
Mar 27 Python
tensorboard实现同时显示训练曲线和测试曲线
Jan 21 Python
使用python的pyplot绘制函数实例
Feb 13 Python
Iconfont(矢量图标)+iconmoon(图标svg互转)配合javascript实现社交分享系统
Apr 21 Python
Python代码中如何读取键盘录入的值
May 27 Python
python 如何调用远程接口
Sep 11 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
php中json_encode UTF-8中文乱码的更好解决方法
2014/09/28 PHP
用PHP写的一个冒泡排序法的函数简单实例
2016/05/26 PHP
encode脚本和normal脚本混用的问题与解决方法
2007/03/08 Javascript
javascript中String类的subString()方法和slice()方法
2011/05/24 Javascript
JQuery的自定义事件代码,触发,绑定简单实例
2013/08/01 Javascript
JavaScript中创建类/对象的几种方法总结
2013/11/29 Javascript
javascript模拟C#格式化字符串
2015/08/26 Javascript
HTML5 Shiv完美解决IE(IE6/IE7/IE8)不兼容HTML5标签的方法
2015/11/25 Javascript
JS onkeypress兼容性写法详解
2016/04/27 Javascript
jQuery和hwSlider实现内容响应式可触控滑动切换效果附源码下载(二)
2016/06/22 Javascript
JS实现用户注册时获取短信验证码和倒计时功能
2016/10/27 Javascript
简单谈谈关于Angular Cli打包的事
2017/09/05 Javascript
详解Webpack-dev-server的proxy用法
2018/09/08 Javascript
使用xampp将angular项目运行在web服务器的教程
2019/09/16 Javascript
对vue生命周期的深入理解
2020/12/03 Vue.js
[03:02]生活中的Dendi之野外度假篇
2016/08/09 DOTA
CentOS中使用virtualenv搭建python3环境
2015/06/08 Python
Python入门_条件控制(详解)
2017/05/16 Python
Python的装饰器使用详解
2017/06/26 Python
python3使用matplotlib绘制散点图
2019/03/19 Python
Django之PopUp的具体实现方法
2019/08/31 Python
wxPython绘图模块wxPyPlot实现数据可视化
2019/11/19 Python
python pygame实现球球大作战
2019/11/25 Python
在python中创建指定大小的多维数组方式
2019/11/28 Python
tensorflow实现残差网络方式(mnist数据集)
2020/05/26 Python
什么是Python中的顺序表
2020/06/02 Python
Python常用数据分析模块原理解析
2020/07/20 Python
HTML5之web workers_动力节点Java学院整理
2017/07/17 HTML / CSS
HTML5 绘制图像(上)之:关于canvas元素引领下一代web页面的问题
2013/04/24 HTML / CSS
英国羊皮鞋类领先品牌:Just Sheepskin
2019/12/12 全球购物
涉外经济法专业毕业生推荐信
2013/11/24 职场文书
电子商务专业个人的自我评价
2013/12/19 职场文书
早读课迟到检讨书
2014/09/25 职场文书
员工考勤管理制度
2015/08/06 职场文书
Python基于Tkinter开发一个爬取B站直播弹幕的工具
2021/05/06 Python
mysql幻读详解实例以及解决办法
2022/06/16 MySQL