Python 그림 은 태풍 경로 시각 화 코드 인 스 턴 스 를 실현 합 니 다.

태풍 은 중대 한 재해 성 날씨 로 태풍 으로 인 한 직접적인 재 해 는 보통 세 가지 측면 에서 발생 한다.광풍,폭우,폭풍 조 를 제외 하고 태풍의 이런 재 해 는 도시 의 침수,집 붕괴,산 홍수,산사태 등 2 차 재 해 를 유발 하기 쉽다.그 렇 기 때문에 태풍 은 과학 연구 와 업무 에서 연구 의 중점 이다.이번 태풍 경로 의 가시 화가 여러분 에 게 약간의 도움 이 되 기 를 바 랍 니 다.
태풍 경로 획득
중국 기상 청(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 년 제1 8 호 태풍 온 비 아 를 그립 니 다.

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])

여러 개의 태풍 경 로 를 그 리 는 방법 을 정의 하고 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)

단일 태풍 gif 경로 변경 방법 을 정의 하고 2018 년 제1 8 호 태풍의 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])

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기