python -- 绘制水平空间分布的脚本(3x3子图)

  • 绘制常用的多子图水平空间分布图的python脚本

包含以下功能

  • 填色图和风场
  • 共享x、y轴
  • 绘制3x3的一共9个子图
  • 设置边框
  • 每个子图分别对应不同的时间
  • 每行子图是相同变量的不同时间数据
  • 添加经纬度信息
  • 添加投影
  • 共用colorbar
def set_tick_params(ax, major_direction='in', minor_direction='out'):
    ax.tick_params(which='major', direction=major_direction, length=3, width=1, pad=5, labelsize=13, bottom=True, left=True, right=True, top=True)
    ax.tick_params(which='minor', direction=minor_direction, bottom=False, left=False, right=False, top=False)
def plot_subplot(ax, data, u, v, title_left, title_right):
    levels = 41
    cmap = cmaps.WhiteBlueGreenYellowRed
    step = 15

    cs = ax.contourf(lon.data, lat.data, data.data, transform=ccrs.PlateCarree(), levels=levels, cmap=cmap)
    ax.quiver(x[::step, ::step], y[::step, ::step], u[::step, ::step].data, v[::step, ::step].data,
              transform=ccrs.PlateCarree())
    ax.set_title(title_left, loc='left')
    ax.set_title(title_right, loc='right')
    return cs

fig, axs = plt.subplots(3, 3, figsize=(15, 7), dpi=200, sharex=True, sharey=True,
                        subplot_kw={'projection': ccrs.PlateCarree(180)})

# Add a map boundary and set ticks
for ax in axs.flat:
    ax.add_feature(cfeature.COASTLINE, linewidth=0.8, edgecolor='black')
    ax.add_feature(cfeature.BORDERS, linewidth=0.5, linestyle='dotted', edgecolor='black')
    ax.set_extent([120, 200, -10, 25], crs=ccrs.PlateCarree())
    ax.set_xticks(np.arange(120, 201, 20), crs=ccrs.PlateCarree())
    ax.set_yticks(np.arange(-10, 26, 10), crs=ccrs.PlateCarree())
    ax.xaxis.set_major_formatter(LongitudeFormatter(zero_direction_label=False))
    ax.yaxis.set_major_formatter(LatitudeFormatter())
    set_tick_params(ax)

# Titles for each row
row_titles = ['Control', 'No_LHR', 'No_BA']
data_sets = [pre_con, pre_rad, pre_ban]
u_sets = [u_con, u_rad, u_ban]
v_sets = [v_con, v_rad, v_ban]

for i, (row_title, data_set, u_set, v_set) in enumerate(zip(row_titles, data_sets, u_sets, v_sets)):
    for j, time_idx in enumerate([4, 16, 20]):
        print(i,j)
        title_left = row_title
        title_right = str(data_set[time_idx].time.data)[:13]
        cs=plot_subplot(axs[i, j], 
                        data_set[time_idx],
                        u_set[time_idx, 0], 
                        v_set[time_idx, 0], title_left, title_right)

# Add a common colorbar to the right of subplots
cax = fig.add_axes([0.985, 0.15, 0.015, 0.75])
cbar = plt.colorbar(cs, cax=cax, orientation='vertical')
cbar.set_label('mm 6hour$^{-1}$', labelpad=15)
cbar.ax.tick_params(which='both',
                  direction='in', )
plt.tight_layout()
plt.show()


fig.savefig('G:/Fig10_windspeed&pre.tiff',format='tiff',
            bbox_inches='tight',dpi=600)

fig.savefig('G:/Fig10_windspeed&pre.svg',format='svg',
            bbox_inches='tight',dpi=600)

你可能感兴趣的:(python常用脚本,python,开发语言)