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中for循环的使用
Apr 14 Python
Python语言的面相对象编程方式初步学习
Mar 12 Python
Python中的并发处理之asyncio包使用的详解
Apr 03 Python
python爬取网页内容转换为PDF文件
Jul 28 Python
python3 kmp 字符串匹配的方法
Jul 07 Python
Python PyAutoGUI模块控制鼠标和键盘实现自动化任务详解
Sep 04 Python
python暴力解压rar加密文件过程详解
Jul 05 Python
Python实现生成密码字典的方法示例
Sep 02 Python
Python字符串中删除特定字符的方法
Jan 15 Python
Python @property装饰器原理解析
Jan 22 Python
python re模块匹配贪婪和非贪婪模式详解
Feb 11 Python
Python的信号库Blinker用法详解
Dec 31 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代码
2013/03/24 PHP
腾讯QQ微博API接口获取微博内容
2013/10/30 PHP
简单实现php上传文件功能
2017/09/21 PHP
JavaScript执行效率与性能提升方案
2012/12/21 Javascript
javascript学习笔记(二)数组和对象部分
2014/09/30 Javascript
jQuery javascript获得网页的高度与宽度的实现代码
2016/04/26 Javascript
jQuery图片渐变特效的简单实现
2016/06/25 Javascript
JavaScript生成.xls文件的代码
2016/12/22 Javascript
简单实现IONIC购物车功能
2017/01/10 Javascript
微信小程序(三):网络请求
2017/01/13 Javascript
ionic中列表项增加和删除的实现方法
2017/01/22 Javascript
Vue.js实现模拟微信朋友圈开发demo
2017/04/20 Javascript
Angular CLI 安装和使用教程
2017/09/13 Javascript
微信小程序当前时间时段选择器插件使用方法详解
2018/12/28 Javascript
ES6基础之数组和对象的拓展实例详解
2019/08/22 Javascript
layui导出所有数据的例子
2019/09/10 Javascript
在Echarts图中给坐标轴加一个标识线markLine
2020/07/20 Javascript
uin-app+mockjs实现本地数据模拟
2020/08/26 Javascript
Django2.1.3 中间件使用详解
2018/11/26 Python
python 实现将文件或文件夹用相对路径打包为 tar.gz 文件的方法
2019/06/10 Python
布隆过滤器的概述及Python实现方法
2019/12/08 Python
Python2和Python3中@abstractmethod使用方法
2020/02/04 Python
CSS3 @media的基本用法总结
2019/09/10 HTML / CSS
瑞典时尚耳机品牌:Urbanears
2017/07/26 全球购物
Jimmy Choo美国官网:周仰杰鞋子品牌
2018/06/08 全球购物
Club Monaco加拿大官网:设计师男女服装
2019/09/29 全球购物
俄罗斯三星品牌商店:Samsungstore
2020/04/05 全球购物
数字天堂软件测试面试题
2012/12/23 面试题
自荐信如何“自荐”
2013/10/24 职场文书
大学生创业计划书的格式要求
2013/12/29 职场文书
新闻专业毕业生英文求职信
2014/03/19 职场文书
网上祭英烈活动总结
2015/02/04 职场文书
2015年建筑工作总结报告
2015/05/04 职场文书
工资证明格式模板
2015/06/12 职场文书
javascript之Object.assign()的痛点分析
2022/03/03 Javascript
如何使用python包中的sched事件调度器
2022/04/30 Python