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中MySQLdb模块用法实例
Nov 10 Python
Python3.4实现从HTTP代理网站批量获取代理并筛选的方法示例
Sep 26 Python
python实现求解列表中元素的排列和组合问题
Mar 15 Python
Python装饰器原理与用法分析
Apr 30 Python
浅谈django orm 优化
Aug 18 Python
python机器学习之KNN分类算法
Aug 29 Python
pandas读取CSV文件时查看修改各列的数据类型格式
Jul 07 Python
VSCode中自动为Python文件添加头部注释
Nov 14 Python
tensorflow模型继续训练 fineturn实例
Jan 21 Python
如何基于Python Matplotlib实现网格动画
Jul 20 Python
scrapy结合selenium解析动态页面的实现
Sep 28 Python
什么是Python装饰器?如何定义和使用?
Apr 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队列用法实例
2014/11/05 PHP
THINKPHP项目开发中的日志记录实例分析
2014/12/01 PHP
php获取ajax的headers方法与内容实例
2017/12/27 PHP
JavaScript中的私有/静态属性介绍
2012/07/26 Javascript
基于JavaScript 类的使用详解
2013/05/07 Javascript
javascript setTimeout和setInterval计时的区别详解
2013/06/21 Javascript
javascript控制层显示或隐藏的方法
2015/07/22 Javascript
JavaScript实现表格快速变色效果代码
2015/08/19 Javascript
为jQuery-easyui的tab组件添加右键菜单功能的简单实例
2016/10/10 Javascript
js正则表达式最长匹配(贪婪匹配)和最短匹配(懒惰匹配)用法分析
2016/12/27 Javascript
angular中的http拦截器Interceptors的实现
2017/02/21 Javascript
js判断数组是否包含某个字符串变量的实例
2017/11/24 Javascript
微信小程序之判断页面滚动方向的示例代码
2018/08/30 Javascript
详解react阻止无效重渲染的多种方式
2018/12/11 Javascript
微信小程序实现收货地址左滑删除
2020/11/18 Javascript
vue双向绑定数据限制长度的方法
2019/11/04 Javascript
js闭包的9个使用场景
2020/12/29 Javascript
[02:39]DOTA2国际邀请赛助威团西雅图第一天
2013/08/08 DOTA
Empty test suite.(PyCharm程序运行错误的解决方法)
2018/11/30 Python
解决python3运行selenium下HTMLTestRunner报错的问题
2018/12/27 Python
selenium+python自动化测试之页面元素定位
2019/01/23 Python
pyqt5 删除layout中的所有widget方法
2019/06/25 Python
如何使用Python 打印各种三角形
2019/06/28 Python
python统计指定目录内文件的代码行数
2019/09/19 Python
Python-jenkins模块之folder相关操作介绍
2020/05/12 Python
Restful_framework视图组件代码实例解析
2020/11/17 Python
CSS去掉A标签(链接)虚线框的方法
2014/04/01 HTML / CSS
大专自我鉴定范文
2013/10/01 职场文书
考试违纪检讨书
2014/02/02 职场文书
《小动物过冬》教学反思
2014/04/17 职场文书
科长竞聘演讲稿
2014/05/16 职场文书
股票投资建议书
2014/05/19 职场文书
红白喜事主持词
2015/07/06 职场文书
CSS3 制作的彩虹按钮样式
2021/04/11 HTML / CSS
微信小程序调用python模型
2022/04/21 Python
python中使用redis用法详解
2022/12/24 Redis