如何将颜色条和标题添加到子图中?

问题描述

如何使用 for 命令为每个图添加颜色条和标题,就像这张图片reference_figure

import numpy as np
import matplotlib.pyplot as plt
import wradlib as wrl
import pyart
import xarray as xr

ds = xr.open_dataset('MDV-20180602-101927-PPIVol.nc')

def sweep(i):
    si = ds.sweep_start_ray_index.values
    ei = ds.sweep_end_ray_index.values
    return slice(si[i],ei[i]+1)

i=0
x = ds.range * np.sin(np.deg2rad(ds.azimuth[sweep(i)]))
y = ds.range * np.cos(np.deg2rad(ds.azimuth[sweep(i)]))

fig,ax = plt.subplots(3,2,figsize=(12,15))
ax = ax.flatten()

variables = ['reflectivity',"veLocity",'zdr','rhohv','phidp','spectral width']

ref = ax[0].pcolormesh(x/1e3,y/1e3,ds['DBZH'][sweep(i)].T,cmap='pyart_NWSRef')
vel = ax[1].pcolormesh(x/1e3,ds['VELH'][sweep(i)].T,cmap='pyart_NWsvel')
zdr = ax[2].pcolormesh(x/1e3,ds['ZDR'][sweep(i)].T,cmap='pyart_RefDiff',vmin=-1,vmax=8)
rho = ax[3].pcolormesh(x/1e3,ds['RHOHV'][sweep(i)].T,vmin=0.5,vmax=1.05)
phidp = ax[4].pcolormesh(x/1e3,ds['PHIDP'][sweep(i)].T,cmap='pyart_Wild25',vmin=-180,vmax=180)
width = ax[5].pcolormesh(x/1e3,ds['WIDTHH'][sweep(i)].T,cmap='pyart_NWS_SPW')

for myax in ax:
    [myax.plot(k * np.cos(ds.azimuth[sweep(i)] * np.pi / 180),k * np.sin(ds.azimuth[sweep(i)] * np.pi / 180),'k-',linewidth=1,alpha=0.5) for k in [25,75,125]]
    myax.set_aspect('equal')

fig.tight_layout()
plt.show()

输出Output

变量是应该使用的标题

解决方法

要获得您想要的标题,您只需在 for 循环中遍历列表即可。所以它应该看起来像下面的变量名。你可以做同样的事情来指定你的其他轴标签。颜色条的工作方式相同,但您需要为每个图使用名称。

variables = ['reflectivity',"velocity",'zdr','rhohv','phidp','spectral width']

subplot_= [ref,vel,zdr,rho,phidp,width)

index=0

for myax in ax:
    [myax.plot(k * np.cos(ds.azimuth[sweep(i)] * np.pi / 180),k * np.sin(ds.azimuth[sweep(i)] * np.pi / 180),'k-',linewidth=1,alpha=0.5) for k in [25,75,125]]
    myax.set_aspect('equal')

    myax.set_title(variables[index]) #Create a title on the axis

    plt.colorbar(subplot_[index],ax=myax)

    index+=1 #Add 1