python 利用cartopy绘制世界地图中部分地区的风场
先看效果图(1982-1984 200hPa高度风场,60°E-150°E,0-40°N)
需要用到的库
import cartopy.crs as ccrs
import cartopy.feature as cf
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
建议使用anaconda安装cartopy
建议使用pip安装netCDF4
绘图过程
设置中文字体(基本每次绘图都要用)
# 设置画图字体的大小
plt.rcParams.update({'font.size': 4})
# 解决中文乱码问题
plt.rcParams['font.sans-serif'] = ['SimHei']
# 解决负号乱码问题
plt.rcParams['axes.unicode_minus'] = False
创建画布
fig = plt.figure(figsize=(2, 2), dpi=400)
指定绘图区域以及中心精度
ax = fig.add_axes([0.2, 0, 0.6, 1], projection=ccrs.PlateCarree(central_longitude=0))
导入相关地图信息
ax.add_feature(cf.LAND.with_scale('110m'))
ax.add_feature(cf.OCEAN.with_scale('110m'))
ax.add_feature(cf.COASTLINE.with_scale('110m'), lw=0.4)
ax.add_feature(cf.RIVERS.with_scale('110m'), lw=0.4)
设置经线纬线样式以及坐标
gl = ax.gridlines(draw_labels=True, linestyle=":", linewidth=0.3, color='k')
导入数据
file = 'DATA.nc'
nc_object = nc.Dataset(file)
lons = nc_object.variables['lon'][:]
lats = nc_object.variables['lat'][:]
u = nc_object.variables['U']
v = nc_object.variables['V']
(读取nc文件有时间再写一篇)
u,v是三维的(时间,高度,纬度,经度)(因为用xgrads转换来的,所以维度是反的)
数据处理
u = np.mean(u, axis=0)[0, :, :]
v = np.mean(v, axis=0)[0, :, :]
先取平均后再取第二层高度,在本次数据中只有两个高度(850hPa和200hPa)
生成网格点
X, Y = np.meshgrid(lons, lats)
绘制风场
q = plt.quiver(X, Y, u, v)
plt.quiver还有很多参数可以调节,具体可见官网quiver
绘制风向标并加注说明
ax.quiverkey(q, 1.1, 0.07, 5, ' ')
plt.text(162, 3, '5m/s', fontsize=4)
自带的说明在本图中与示例箭头距离稍远,故自己plt.text一个说明
设置标题,x,y轴的title
plt.title('1982-1984 JJA wind')
plt.xlabel('lon')
plt.ylabel('lat')
plt.show()
整段代码
import cartopy.crs as ccrs
import cartopy.feature as cf
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
# 设置画图字体的大小
plt.rcParams.update({'font.size': 4})
# 解决中文乱码问题
plt.rcParams['font.sans-serif'] = ['SimHei']
# 解决负号乱码问题
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure(figsize=(2, 2), dpi=400)
ax = fig.add_axes([0.2, 0, 0.6, 1], projection=ccrs.PlateCarree(central_longitude=0))
ax.add_feature(cf.LAND.with_scale('110m'))
ax.add_feature(cf.OCEAN.with_scale('110m'))
ax.add_feature(cf.COASTLINE.with_scale('110m'), lw=0.4)
ax.add_feature(cf.RIVERS.with_scale('110m'), lw=0.4)
gl = ax.gridlines(draw_labels=True, linestyle=":", linewidth=0.3, color='k')
ax.set_title('gridlines经纬度风格', fontsize=2)
file = 'DATA.nc'
nc_object = nc.Dataset(file)
lons = nc_object.variables['lon'][:]
lats = nc_object.variables['lat'][:]
u = nc_object.variables['U']
v = nc_object.variables['V']
print(u.shape)
u = np.mean(u, axis=0)[1, :, :]
v = np.mean(v, axis=0)[1, :, :]
X, Y = np.meshgrid(lons, lats)
q = plt.quiver(X, Y, u, v)
ax.quiverkey(q, 1.1, 0.07, 30, ' ')
plt.text(162, 3, '5m/s', fontsize=4)
plt.title('1982-1984 JJA wind')
plt.xlabel('lon')
plt.ylabel('lat')
plt.show()