利用windrose叠加污染物浓度
1. 效果图
在大气环境领域经常需要画一种风向玫瑰叠加污染物浓度的图,周末用python试了试,也是非常简单好用。
2. 代码解析
2.1 导入库和读取数据
除了分析和读取数据的numpy, pandas还有matplotlib外,需要添加windrose库,这点可以自己pip install windrose,比较简单方便。
另外,准备了3列数据,分别代表风向wd, 风速ws,污染物浓度pm。这里wd用到的是弧度数据(0-2pi)。
from windrose import WindroseAxes
from matplotlib import pyplot as plt
import matplotlib as mpl
import numpy as np
import pandas as pd
mpl.rcParams["font.family"] = 'Arial' #默认字体类型
mpl.rcParams["mathtext.fontset"] = 'cm' #数学文字字体
mpl.rcParams["font.size"] = 16
# read data
data = pd.read_excel("wind.xlsx", index_col=0, sheet_name='Sheet2').dropna()
ws = data.ws
wd = data.wd/360*2*np.pi
pm = data.O3
2.2 转变为windrose轴
ax = WindroseAxes.from_ax()把轴换成windrose轴,此时还需做以下三步完成转换:
- 把0°方向定位北:ax.set_theta_zero_location(“N”)
- 坐标旋转方向为clockwise
- 定义具体的坐标间隔和label
fig = plt.figure(figsize=(6,6))
ax = WindroseAxes.from_ax()
ax.set_theta_zero_location("N")
ax.set_theta_direction('clockwise')
ax.set_xticks([(i/4)*np.pi for i in range(8)])
ax.set_xticklabels(['N','NE','E','SE','S','SW','W','NW'])
ax.set_rlim(0,8)
2.3 画散点填色图
画散点图,c=pm把污染物浓度和散点填色结合起来,cmap选择colormap,s为散点大小。
添加colorbar,定义长度(shrink)和与图片的距离(pad).
plt.scatter(wd, ws, c=pm, cmap='jet', alpha=0.9, s=200)
plt.colorbar(shrink=0.75, pad=0.07)
plt.savefig('wind_scatter.png')
3. 完整代码
from windrose import WindroseAxes
from matplotlib import pyplot as plt
import matplotlib as mpl
import numpy as np
import pandas as pd
mpl.rcParams["font.family"] = 'Arial' #默认字体类型
mpl.rcParams["mathtext.fontset"] = 'cm' #数学文字字体
mpl.rcParams["font.size"] = 16
# read data
data = pd.read_excel("wind.xlsx", index_col=0, sheet_name='Sheet2').dropna()
ws = data.ws
wd = data.wd/360*2*np.pi
pm = data.O3
# plot
fig = plt.figure(figsize=(6,6))
ax = WindroseAxes.from_ax()
ax.set_theta_zero_location("N")
ax.set_theta_direction('clockwise')
ax.set_xticks([(i/4)*np.pi for i in range(8)])
ax.set_xticklabels(['N','NE','E','SE','S','SW','W','NW'])
ax.set_rlim(0,8)
plt.scatter(wd, ws, c=pm, cmap='jet', alpha=0.9, s=200)
plt.colorbar(shrink=0.75, pad=0.07)
plt.savefig('wind_scatter.png')