import os
import pandas as pd
import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像时负号'-'显示为方块的问题
# 设定默认字体大小为12
plt.rcParams['font.size'] = 12
import cartopy.crs as ccrs
import cartopy.feature as cfeat
from matplotlib.lines import Line2D
from matplotlib.collections import LineCollection
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
# 读取数据
df = pd.read_csv('D:/data/2024_TY2403.csv')
# 假设正确的列名是 'grade' 而不是 'grade_at_point',并且它表示每个点的强度级别
# 如果不是,请替换为正确的列名
# 定义颜色函数
def get_color(grade):
if grade == '热带低压' or grade == '热带扰动':
return '#FFFF00'
elif grade == '热带风暴':
return '#6495ED'
elif grade == '强热带风暴':
return '#3CB371'
elif grade == '台风':
return '#FFA500'
elif grade == '强台风':
return '#FF00FF'
elif grade == '超强台风':
return '#DC143C'
# 创建地图并绘制台风路径
def plot_typhoons(df, extent):
gdf = gpd.read_file('D:/data/中国_省.shp')
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
# 添加底图
ax.add_feature(cfeat.COASTLINE)
# 添加中国省界
gdf.boundary.plot(ax=ax, transform=ccrs.PlateCarree(), linewidth=0.5, edgecolor='black')
# 设置地图范围
ax.set_extent(extent, crs=ccrs.PlateCarree())
# 添加网格线
gl = ax.gridlines(draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='--')
gl.xlabels_top = gl.ylabels_right = False
# 设置经纬度格式和刻度
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.yaxis.set_major_formatter(LatitudeFormatter())
# 绘制台风路径
for tc_num, group in df.groupby('tc_num'):
points = np.array(list(zip(group['lon'], group['lat'])))
if 'grade' in group.columns: # 确保 'grade' 列存在
colors = [get_color(grade) for grade in group['grade']] # 使用 'grade' 列
else:
# 如果没有 'grade' 列,可以使用默认颜色或其他逻辑
colors = ['#000000'] * len(points) # 例如,使用黑色
segments = np.array([points[i:i+2] for i in range(len(points)-1)])
lc = LineCollection(segments, colors=colors, linewidths=2)
ax.add_collection(lc)
# 添加图例(这里需要手动指定,因为使用了循环绘制)
legend_elements = [
Line2D([], [], color='#FFFF00', marker='o', label='热带低压/扰动', markersize=5),
Line2D([], [], color='#6495ED', marker='o', label='热带风暴', markersize=5),
Line2D([], [], color='#3CB371', marker='o', label='强热带风暴', markersize=5),
Line2D([], [], color='#FFA500', marker='o', label='台风', markersize=5),
Line2D([], [], color='#FF00FF', marker='o', label='强台风', markersize=5),
Line2D([], [], color='#DC143C', marker='o', label='超强台风', markersize=5),
]
ax.legend(handles=legend_elements, loc='upper left')
# 设置标题
plt.title('2403台风格美路径')
# 显示图形
plt.show()
# 调用函数,替换 extent 为所需的经纬度范围
plot_typhoons(df, extent=[100, 150, 0, 40]) # 根据需要设置extent
绘制台风路径(二)
于 2024-07-25 19:14:28 首次发布