# 使用Matplotlib & Cartopy绘制台风路径图

image.png

## 主要第三方库

`cartopy`：基于matplotlib的python地理数据处理和可视化库，本文会用来展示地图

`shapely`: 是一个对几何对象进行操作和分析的Python库，本文用来处理点线数据

## 绘制地图

``````# cartopy：用来获取地图
import cartopy.crs as ccrs
import cartopy.feature as cfeature
# matplotlib：用来绘制图表
import matplotlib.pyplot as plt
# shapely：用来处理点线数据
import shapely.geometry as sgeom
import warnings
import re
import numpy as np
import pandas as pd
warnings.filterwarnings('ignore')
plt.rcParams['font.sans-serif'] = [u'SimHei']
plt.rcParams['axes.unicode_minus'] = False
``````

``````# 通过cartopy获取底图
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())

# 用经纬度对地图区域进行截取，这里只展示我国沿海区域
ax.set_extent([85,170,-20,60], crs=ccrs.PlateCarree())

# 设置名称
ax.set_title('2017年台风路径图',fontsize=16)

# 设置地图属性，比如加载河流、海洋

# 展示地图
plt.show()
``````

## 处理数据并可视化

``````typhoonData = pd.read_csv('typhoonData.csv')
``````

``````# 先对台风编号进行循环，提取单个台风数据
for typhoonNumber in typhoonData['台风编号'].unique():
typhoon = typhoonData[typhoonData['台风编号']==typhoonNumber]
# 再对单个台风数据进行处理，提取经纬度
for typhoonPoint in np.arange(len(typhoon)-1):
lat_1 = typhoon.iloc[typhoonPoint,3]/10
lon_1 = typhoon.iloc[typhoonPoint,4]/10
lat_2 = typhoon.iloc[typhoonPoint+1,3]/10
lon_2 = typhoon.iloc[typhoonPoint+1,4]/10
point_1 = lon_1,lat_1
point_2 = lon_2,lat_2
# 最后可视化

# 展示图像
plt.show()
``````

• 用颜色区别：不同颜色代表不同强度，参数-edgecolor
• 用线条粗细区别：越粗则强度越高，参数-linewidth
1. 颜色区分
``````# 按强度区分颜色
def get_color(level):
if level in (0,1):
color='#ff00ff'
elif level in (2,3):
color='#ff00cc'
elif level in (4,5):
color='#ff0066'
elif level in (6,7):
color='#ff0033'
elif level in (8,9):
color='#ccff00'
return color

# 先对台风编号进行循环，提取单个台风数据
for typhoonNumber in typhoonData['台风编号'].unique():
typhoon = typhoonData[typhoonData['台风编号']==typhoonNumber]
# 再对单个台风数据进行处理，提取经纬度
for typhoonPoint in np.arange(len(typhoon)-1):
lat_1 = typhoon.iloc[typhoonPoint,3]/10
lon_1 = typhoon.iloc[typhoonPoint,4]/10
lat_2 = typhoon.iloc[typhoonPoint+1,3]/10
lon_2 = typhoon.iloc[typhoonPoint+1,4]/10
point_1 = lon_1,lat_1
point_2 = lon_2,lat_2
# 最后可视化，添加颜色参数

# 展示图像
plt.show()
``````
1. 线条粗细区分
``````# 先对台风编号进行循环，提取单个台风数据
for typhoonNumber in typhoonData['台风编号'].unique():
typhoon = typhoonData[typhoonData['台风编号']==typhoonNumber]
# 再对单个台风数据进行处理，提取经纬度
for typhoonPoint in np.arange(len(typhoon)-1):
lat_1 = typhoon.iloc[typhoonPoint,3]/10
lon_1 = typhoon.iloc[typhoonPoint,4]/10
lat_2 = typhoon.iloc[typhoonPoint+1,3]/10
lon_2 = typhoon.iloc[typhoonPoint+1,4]/10
point_1 = lon_1,lat_1
point_2 = lon_2,lat_2
# 最后可视化