绘制风廓线雷达图

第一步

import numpy as np
import pandas as pd
import matplotlib as mpl
import cmaps

import os
import math
import glob
import datetime
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

第二步 定义一些函数

transform=lambda x:x.to_pydatetime().replace(second=0)

def truncate_colormap(cmapIn='jet', minval=0.0, maxval=1.0, n=100):
    '''truncate_colormap(cmapIn='jet', minval=0.0, maxval=1.0, n=100)'''
    cmapIn = plt.get_cmap(cmapIn)

    new_cmap = mpl.colors.LinearSegmentedColormap.from_list(
        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmapIn.name, a=minval, b=maxval),
        cmapIn(np.linspace(minval, maxval, n)))

    return new_cmap

### 画十分钟平均图

def read_plot_windlidar(windlidar,fname,num):
    
    new_jet = truncate_colormap('jet', minval=0.25, maxval=0.9, n=100)
    
    zwind = windlidar.iloc[:,np.arange(15,1534,9)].copy()   ### 筛选出各层垂直风速
    WS = windlidar.iloc[:,np.arange(8,1525,9)].copy()    ### 筛选出各层水平风速
    WD = windlidar.iloc[:,np.arange(9,1525,9)].copy()  ### 筛选出各层水平风向
    
    WS[WS<0] = np.nan
    WD[(WD<0)|(WD>360)] = np.nan
    # zwind[(zwind<-5)|(zwind>5)] = np.nan
    
    path2 = r"D:\wuhai_hgt.csv"    ### 每层的高度信息
    hgt = pd.read_csv(path2,header = 0)

    ### 根据水平风速风向计算u,v分量

    rad = np.pi/180.0
    WD.columns = WS.columns ## 为了计算u,v

    u = -WS*np.sin(WD*rad)
    v = -WS*np.cos(WD*rad)
      
    
    #### 绘制平面图部分  10min
    if num==0:
        uwind = u.T.values
        vwind = v.T.values
        ws_mean = WS
        n=6
    else:        ### 1hour
        u_mean = u.resample("H").mean()   
        v_mean = v.resample("H").mean()   
        w_mean = zwind.resample("H").mean() 

     #### 将u,v平均转换为风向风速
        deg = 180.0/np.pi

        ws_mean =(u_mean*u_mean+v_mean*v_mean).apply(np.sqrt)
        wd_mean = 180+np.arctan2(u_mean,v_mean)*deg

    #### 绘制平面图部分
        uwind = u_mean.T.values
        vwind = v_mean.T.values
        zwind = w_mean
        n=3


    fig,axs = plt.subplots(nrows=2,ncols=1,figsize=(40,20))
    mpl.rcParams['font.size'] = 15
    mpl.rcParams['font.weight'] = 'bold'
    mpl.rcParams['font.sans-serif']=['Arial']

    xtime = pd.to_datetime(ws_mean.index)
    X,Y   = np.meshgrid(xtime,hgt)

    cs   = axs[0].contourf(X,Y,ws_mean.T,levels = list(np.arange(0,12,0.1)),cmap = new_jet)
    cbar = fig.colorbar(cs,ax = axs[0],shrink=0.9,pad=0.01)
    cbar.set_label('Wind speed(m/s)',fontsize=14,font="Arial")
    cbar.set_ticks(np.linspace(0,12, 7))
    cbar.ax.tick_params(labelsize=14)

    q = axs[0].quiver(X[::n], Y[::n],uwind[::n], vwind[::n],scale =950,
                  color='k',width=0.0005, headwidth=2, headlength=4.,
                 minshaft = 3)

    axs[0].quiverkey(q, X=0.95, Y=0.95, U = 5,label='5 m/s', labelpos='E')

    ##########################################
    cs2   = axs[1].contourf(X,Y,zwind.T,levels = list(np.arange(-2,2,0.01)),cmap = new_jet)
    cbar2 = fig.colorbar(cs2,ax = axs[1],shrink=0.9,pad = 0.01)

    cbar2.set_label('Vertical speed(m/s)',fontsize=14,font="Arial")
    cbar2.set_ticks([-1.5,-1,-0.5,0,0.5,1,1.5])
    cbar2.ax.tick_params(labelsize=14)

    majorloc = mdates.DayLocator(interval=3)
    majorFormatter = DateFormatter('%m-%d')

    for ax in axs:
        ax.xaxis.set_major_locator(majorloc)
        ax.xaxis.set_major_formatter(majorFormatter)
        ax.xaxis.set_minor_locator(mdates.HourLocator(interval=12)) 
        ax.set_ylabel('Height (m)')
        ax.set_ylim(0, 2000)
        ax.tick_params(which='major',length=8,width=1.3,labelsize=15,pad=8) 
        ax.tick_params(which='minor',length=4,width=1.1,labelsize=15,pad=8)

        fig.align_ylabels(axs)
    
    outf=r'D:\wind-'+fname
    fig.savefig(outf,bbox_inches = 'tight',dpi=200)   
    plt.close()

第三步 读取数据

path = r"D:\北京风廓线雷达0817-1005"
fname = ["*.csv"]

year = "2022"
month = ["08","09","10"]
monthnum = [31,30,5]

day= []
for i in range(1,32):
        day.append(str(i).rjust(2,'0')) 

path1 =[]               
for i in [0,1,2]: 
        for j in range(monthnum[i])    
            datestr  = year+month[i]+day[j]+"\level3"
            path1.append(os.path.join(path,datestr))
path1 = path1[16:]

def read_winddata(path_date,filename):
    db=[]
    for i in np.arange(50):
        if i==4:
            continue
        f = glob.glob(os.path.join(path_date[i],filename))
#         print(f)
        db.append(pd.read_csv(f[0],header=0,skiprows=1,date_parser=[0,1],na_values=999))
    windlidar = pd.concat(db)
    
    windlidar["Date_time"] = pd.to_datetime(windlidar["Date_time"])
    windlidar = windlidar.set_index(["Date_time"])
    windlidar.index = windlidar.index.map(transform)  ### 将秒统一为00
    windlidar[windlidar==999]=np.nan  ### 缺省值999
    
    return windlidar


fname = ["*.csv"]
outf = read_winddata(path1,fname[0])

第四步 绘图

figname = "wind_0817-1005.png"
read_plot_windlidar(outf,figname,0) ### 画10min平均图
read_plot_windlidar(outf,figname,0) ### 画小时平均图

你可能感兴趣的:(绘制风廓线雷达图)