Python 风场高度场温度场图(单图和子图)

本文介绍了如何使用Python库如matplotlib和cartopy从netCDF文件中提取气象数据(如位势高度、风场和气温),并创建包含这些变量的地图,展示了不同时间点和水平层的数据可视化。
摘要由CSDN通过智能技术生成

单图

# -*- coding: utf-8 -*-
"""
@Features: 
@Author:   xxx
@Date:    4/7/2024
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import netCDF4 as nc
import cartopy.feature as cfeature
import cartopy.crs as ccrs
from matplotlib.colors import Normalize

plt.rcParams['font.family'] = 'Times New Roman, SimSun'  # 设置字体族,中文为SimSun,英文为Times New Roman
plt.rcParams['mathtext.fontset'] = 'stix'  # 设置数学公式字体为stix

if __name__ == '__main__':
    # 读取netCDF文件
    filename = 'data.nc'  # 替换为你的数据文件路径
    dataset = nc.Dataset(filename)

    # 提取变量
    height = dataset.variables['z'][:]  # 位势高度,替换为你的变量名
    u_wind = dataset.variables['u'][:]  # u分量风场,替换为你的变量名
    v_wind = dataset.variables['v'][:]  # v分量风场,替换为你的变量名
    temperature = dataset.variables['t'][:] - 273.15  # 气温,替换为你的变量名
    level = dataset.variables['level'][:]
    time = dataset.variables['time']  # 读取时间
    real_time = nc.num2date(time, time.units).data  # 转成时间格式

    # 获取经纬度
    lon = dataset.variables['longitude'][:]
    lat = dataset.variables['latitude'][:]

    time_index = [37, 61, 78, 92]
    height_index = [0, 4, 9, 15]
    # 绘制位势高度

    for t in time_index:
        for h in height_index:
            print(t, h)
            # 设置绘图区域和投影
            fig = plt.figure(figsize=(12, 6))
            ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
            ax.add_feature(cfeature.LAND)
            ax.add_feature(cfeature.OCEAN)
            ax.add_feature(cfeature.COASTLINE)
            ax.add_feature(cfeature.BORDERS, linestyle=':')

            c1 = ax.contour(lon, lat, height[t, h, :, :], levels=20, transform=ccrs.PlateCarree())
            # 在等值线上标出数值
            ax.clabel(c1, inline=True, fontsize=9)

            # 绘制气温
            # temperature_norm = Normalize(vmin=np.min(temperature[1, 1, :, :]), vmax=np.max(temperature[1, 1, :, :]))
            c2 = ax.contourf(lon, lat, temperature[t, h, :, :], levels=10, cmap='coolwarm',
                             alpha=0.8, transform=ccrs.PlateCarree())
            # 绘制风场
            ax.quiver(lon[::10], lat[::10], u_wind[t, h, ::10, ::10], v_wind[t, h, ::10, ::10],
                      transform=ccrs.PlateCarree())
            # 添加色标
            # cbar_ax = fig.add_axes([0.9, 0.15, 0.03, 0.7])
            # fig.colorbar(c1, cax=cbar_ax, label='Geopotential Height (m)')
            fig.colorbar(c2, label='Temperature (℃)', location='right')

            # 设置标题
            ax.set_title('Geopotential Height, Wind Field, and Temperature')
            ax.set_xticks(np.arange(lon[0], lon[-1], 10), crs=ccrs.PlateCarree())
            ax.set_yticks(np.arange(lat[-1], lat[0], 10), crs=ccrs.PlateCarree())

            # 显示图形
            # plt.show()
            plt.savefig(r'H:\pic\UTC-' + str(real_time[t])[:13] + '-Level-' + str(level[h]) + '.png')


在这里插入图片描述

多图

# -*- coding: utf-8 -*-
"""
@Features: 
@Author:  
@Date:    2024/5/26
"""

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import netCDF4 as nc
import cartopy.feature as cfeature
import cartopy.crs as ccrs
from matplotlib.colors import Normalize

plt.rcParams['font.family'] = 'Times New Roman, SimSun'  # 设置字体族,中文为SimSun,英文为Times New Roman
plt.rcParams['mathtext.fontset'] = 'stix'  # 设置数学公式字体为stix

if __name__ == '__main__':
    # 读取netCDF文件
    filename = 'data.nc'  # 替换为你的数据文件路径
    dataset = nc.Dataset(filename)

    # 提取变量
    height = dataset.variables['z'][:]  # 位势高度,替换为你的变量名
    u_wind = dataset.variables['u'][:]  # u分量风场,替换为你的变量名
    v_wind = dataset.variables['v'][:]  # v分量风场,替换为你的变量名
    temperature = dataset.variables['t'][:] - 273.15  # 气温,替换为你的变量名
    level = dataset.variables['level'][:]
    time = dataset.variables['time']  # 读取时间
    real_time = nc.num2date(time, time.units).data  # 转成时间格式

    # 获取经纬度
    lon = dataset.variables['longitude'][:]
    lat = dataset.variables['latitude'][:]

    time_index = [37, 61, 72, 78, 92]
    height_index = [0, 4, 9, 15]
    # 绘制位势高度

    for t in time_index:
        # fig, axes = plt.subplots(2, 2, figsize=(12, 6))
        # ax = axes.flat
        fig = plt.figure(figsize=(12, 10))
        for index, h in enumerate(height_index, start=1):
            print(t, h)
            # draw(axes[0, 0], t, h)

            # 设置绘图区域和投影
            ax = fig.add_subplot(2, 2, index, projection=ccrs.PlateCarree())
            ax.add_feature(cfeature.LAND)
            ax.add_feature(cfeature.OCEAN)
            ax.add_feature(cfeature.COASTLINE)
            ax.add_feature(cfeature.BORDERS, linestyle=':')

            c1 = ax.contour(lon, lat, height[t, h, :, :], levels=20, transform=ccrs.PlateCarree())
            # 在等值线上标出数值
            ax.clabel(c1, inline=True, fontsize=9)

            # 绘制气温
            # temperature_norm = Normalize(vmin=np.min(temperature[1, 1, :, :]), vmax=np.max(temperature[1, 1, :, :]))
            c2 = ax.contourf(lon, lat, temperature[t, h, :, :], levels=10, cmap='coolwarm',
                             alpha=0.8, transform=ccrs.PlateCarree())
            # 绘制风场
            ax.quiver(lon[::10], lat[::10], u_wind[t, h, ::10, ::10], v_wind[t, h, ::10, ::10],
                      transform=ccrs.PlateCarree())
            # 添加色标
            # cbar_ax = fig.add_axes([0.9, 0.15, 0.03, 0.7])
            # fig.colorbar(c1, cax=cbar_ax, label='Geopotential Height (m)')
            cb = fig.colorbar(c2, label='Temperature (℃)', location='right', shrink=0.6)
            # 注意这里我们使用 colorbar.ax.yaxis.label,因为标签是 Y 轴的一部分
            cb.ax.yaxis.label.set_size(14)  # 14 是字体大小,你可以根据需要调整
            # 如果你还想修改刻度标签的字体大小,可以这样做:
            for tick in cb.ax.get_yticklabels():
                tick.set_fontsize(18)  # 设置刻度标签的字体大小为12

            # 设置标题
            ax.set_title('Geopotential Height, Wind Field, and Temperature')
            ax.set_xticks(np.arange(lon[0], lon[-1], 10), crs=ccrs.PlateCarree())
            ax.tick_params(axis='x', labelsize=18)  # 设置x轴刻度标签字体大小为12
            ax.set_yticks(np.arange(lat[-1], lat[0], 10), crs=ccrs.PlateCarree())
            ax.tick_params(axis='y', labelsize=18)  # 设置y轴刻度标签字体大小为12
            ax.text(0.05, 0.95, "("+chr(ord('a') + index-1)+")", transform=ax.transAxes, fontsize=14,
                    va='top', ha='left', bbox=dict(boxstyle='round', facecolor='white', edgecolor='0.3', alpha=0.8))
            plt.tight_layout()
            # 显示图形
        plt.show()

在这里插入图片描述

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值