python - - 绘制垂直剖面图的脚本

  • 把日常用的绘图脚本在这里做个记录,方面下次直接粘贴复制
  • 该脚本主要为绘制经度-时间的二维剖面图

四个子图,涉及一些图片的美化

  • 边框加粗
  • 边框方向调整朝内
  • 添加colorbar
  • 添加小标题
  • 添加经度信息
  • 添加colorbar,colorbar边框加粗
  • 设置cmap
  • 设置填色范围
  • 添加散点
import matplotlib.pyplot as plt
from matplotlib.ticker import LongitudeFormatter
import numpy as np

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 get_tickset(ax, x, title1, title2, xlim, xticks):
    ax.invert_yaxis()
    ax.set_xticks(xticks)
    ax.set_xlim(xlim)
    ax.xaxis.set_major_formatter(LongitudeFormatter(zero_direction_label=False))
    set_tick_params(ax)
    n = len(x)
    y = [990] * n
    ax.scatter(x, y, marker='^', color='blue', alpha=0.75, s=10)
    ax.grid(alpha=0.1)
    ax.grid([])
    ax.spines[['right', 'left', 'top', 'bottom']].set_linewidth(1.3)
    ax.spines[['right', 'left', 'top', 'bottom']].set_visible(True)
    ax.set_title(title1, loc='left',)
    ax.set_title(title2, loc='right')

def set_colorbar(conf, ax):
    ticklabels = [-0.5, 0, 0.5]
    cb = fig.colorbar(conf, ax=ax, orientation='vertical', format='%.2f')
    cb.ax.tick_params(which='major', labelsize=13, pad=13, direction='in', width=0, length=10)
    cb.outline.set_linewidth(0.75)

def plot_data(ax, lon_q, level, data, vor_data, lon_range, title_prefix, xlim, xticks, cmap, levels):
    conf = ax.contourf(lon_q, level, data, levels=levels, cmap=cmap, extend='both')
    ax.contour(lon_q, level, vor_data, colors='k', linewidths=0.7)
    get_tickset(ax, lon_range, f'({title_prefix})', 'Q_total & Relative Vorticity', xlim, xticks)
    set_colorbar(conf, ax)

def generate_subplot(ax, lon_q, level, q_data, vor_data, lon_range, title_prefix, xlim, xticks, cmap, levels):
    plot_data(ax, lon_q, level, q_data, vor_data, lon_range, title_prefix, xlim, xticks, cmap, levels)

# Example usage:
fig, axs = plt.subplots(2, 2, dpi=200, figsize=(12, 10))
lon_center_slice1 = lon_center[8:19]
lon_center_slice2 = lon_center[19:26]

generate_subplot(axs[0, 0], lon_q, level, q_m, vor_m, lon_center_slice1, 'a) MRG', (120, 200), np.arange(120, 220, 20), cmaps.BlueWhiteOrangeRed, np.linspace(-2, 2, 17))
generate_subplot(axs[0, 1], lon_q, level, q_m_td, vor_m_td, lon_center_slice2, 'b) TD', (120, 200), np.arange(120, 220, 20), cmaps.BlueWhiteOrangeRed, np.linspace(-2, 2, 17))
generate_subplot(axs[1, 0], lon_q, level, q_m, vor_m, lon_center_slice1, 'a) MRG', (150, 170), np.arange(150, 171, 5), cmaps.BlueWhiteOrangeRed, np.linspace(-2, 2, 17))
generate_subplot(axs[1, 1], lon_q, level, q_m_td, vor_m_td, lon_center_slice2, 'b) TD', (145, 156), np.arange(145, 156, 5), cmaps.BlueWhiteOrangeRed, np.linspace(-2, 2, 17))

plt.show()

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