气ython风雨 发表于 2024-5-1 21:33:35

matplotlib:怎么画带白色框的等值线


========================================

前言
有读者问我怎么画出带白色框的等值线,他在微博刷到一张图,如下



关键函数:set_box()
下面结合GFS资料画一个500hPa的高度图为例

导入库与链接数据库
In :

# Resolve the latest GFS dataset
import metpy
from siphon.catalog import TDSCatalog
from datetime import datetime

import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import metpy.calc as mpcalc
from metpy.units import units
from netCDF4 import num2date
import numpy as np
import scipy.ndimage as ndimage
from siphon.ncss import NCSS
from siphon.catalog import TDSCatalog
# Set up access via NCSS
gfs_catalog = ('http://thredds.ucar.edu/thredds/catalog/grib/NCEP/GFS/'
               'Global_0p5deg/catalog.xml?dataset=grib/NCEP/GFS/Global_0p5deg/Best')
cat = TDSCatalog(gfs_catalog)
ncss = cat.datasets.subset()

In :
ncss.variables

Out:
{'Absolute_vorticity_isobaric',
'Albedo_surface_Mixed_intervals_Average',
'Apparent_temperature_height_above_ground',
'Best_4_layer_Lifted_Index_surface',
'Categorical_Freezing_Rain_surface',
'Categorical_Freezing_Rain_surface_Mixed_intervals_Average',
'Categorical_Ice_Pellets_surface',
'Categorical_Ice_Pellets_surface_Mixed_intervals_Average',
'Categorical_Rain_surface',
'Categorical_Rain_surface_Mixed_intervals_Average',
'Categorical_Snow_surface',
'Categorical_Snow_surface_Mixed_intervals_Average',
'Cloud_Work_Function_entire_atmosphere_single_layer_Mixed_intervals_Average',
'Cloud_mixing_ratio_hybrid',
'Cloud_mixing_ratio_isobaric',
'Cloud_water_entire_atmosphere_single_layer',
'Composite_reflectivity_entire_atmosphere',
'Convective_Precipitation_Rate_surface_Mixed_intervals_Average',
'Convective_available_potential_energy_pressure_difference_layer',
'Convective_available_potential_energy_surface',
'Convective_inhibition_pressure_difference_layer',
'Convective_inhibition_surface',
'Convective_precipitation_rate_surface',
'Convective_precipitation_surface_Mixed_intervals_Accumulation',
'Dewpoint_temperature_height_above_ground',
'Downward_Long-Wave_Radp_Flux_surface_Mixed_intervals_Average',
'Downward_Short-Wave_Radiation_Flux_surface_Mixed_intervals_Average',
'Field_Capacity_surface',
'Frictional_Velocity_surface',
'Geopotential_height_cloud_ceiling',
'Geopotential_height_highest_tropospheric_freezing',
'Geopotential_height_isobaric',
'Geopotential_height_maximum_wind',
'Geopotential_height_potential_vorticity_surface',
'Geopotential_height_surface',
'Geopotential_height_tropopause',
'Geopotential_height_zeroDegC_isotherm',
'Graupel_snow_pellets_hybrid',
'Graupel_snow_pellets_isobaric',
'Ground_Heat_Flux_surface_Mixed_intervals_Average',
'Haines_index_surface',
'High_cloud_cover_high_cloud',
'High_cloud_cover_high_cloud_Mixed_intervals_Average',
'ICAO_Standard_Atmosphere_Reference_Height_maximum_wind',
'ICAO_Standard_Atmosphere_Reference_Height_tropopause',
'Ice_cover_surface',
'Ice_growth_rate_altitude_above_msl',
'Ice_temperature_surface',
'Ice_thickness_surface',
'Ice_water_mixing_ratio_hybrid',
'Ice_water_mixing_ratio_isobaric',
'Land_cover_0__sea_1__land_surface',
'Latent_heat_net_flux_surface_Mixed_intervals_Average',
'Liquid_Volumetric_Soil_Moisture_non_Frozen_depth_below_surface_layer',
'Low_cloud_cover_low_cloud',
'Low_cloud_cover_low_cloud_Mixed_intervals_Average',
'MSLP_Eta_model_reduction_msl',
'Maximum_temperature_height_above_ground_Mixed_intervals_Maximum',
'Medium_cloud_cover_middle_cloud',
'Medium_cloud_cover_middle_cloud_Mixed_intervals_Average',
'Meridional_Flux_of_Gravity_Wave_Stress_surface_Mixed_intervals_Average',
'Minimum_temperature_height_above_ground_Mixed_intervals_Minimum',
'Momentum_flux_u-component_surface_Mixed_intervals_Average',
'Momentum_flux_v-component_surface_Mixed_intervals_Average',
'Ozone_Mixing_Ratio_isobaric',
'Per_cent_frozen_precipitation_surface',
'Planetary_Boundary_Layer_Height_surface',
'Plant_Canopy_Surface_Water_surface',
'Potential_Evaporation_Rate_surface',
'Potential_temperature_sigma',
'Precipitable_water_entire_atmosphere_single_layer',
'Precipitation_rate_surface',
'Precipitation_rate_surface_Mixed_intervals_Average',
'Pressure_convective_cloud_bottom',
'Pressure_convective_cloud_top',
'Pressure_height_above_ground',
'Pressure_high_cloud_bottom_Mixed_intervals_Average',
'Pressure_high_cloud_top_Mixed_intervals_Average',
'Pressure_low_cloud_bottom_Mixed_intervals_Average',
'Pressure_low_cloud_top_Mixed_intervals_Average',
'Pressure_maximum_wind',
'Pressure_middle_cloud_bottom_Mixed_intervals_Average',
'Pressure_middle_cloud_top_Mixed_intervals_Average',
'Pressure_of_level_from_which_parcel_was_lifted_pressure_difference_layer',
'Pressure_potential_vorticity_surface',
'Pressure_reduced_to_MSL_msl',
'Pressure_surface',
'Pressure_tropopause',
'Rain_mixing_ratio_hybrid',
'Rain_mixing_ratio_isobaric',
'Reflectivity_height_above_ground',
'Reflectivity_hybrid',
'Relative_humidity_entire_atmosphere_single_layer',
'Relative_humidity_height_above_ground',
'Relative_humidity_highest_tropospheric_freezing',
'Relative_humidity_isobaric',
'Relative_humidity_pressure_difference_layer',
'Relative_humidity_sigma',
'Relative_humidity_sigma_layer',
'Relative_humidity_zeroDegC_isotherm',
'Sensible_heat_net_flux_surface_Mixed_intervals_Average',
'Snow_depth_surface',
'Snow_mixing_ratio_hybrid',
'Snow_mixing_ratio_isobaric',
'Soil_temperature_depth_below_surface_layer',
'Soil_type_surface',
'Specific_humidity_height_above_ground',
'Specific_humidity_isobaric',
'Specific_humidity_pressure_difference_layer',
'Storm_relative_helicity_height_above_ground_layer',
'Sunshine_Duration_surface',
'Surface_Lifted_Index_surface',
'Surface_roughness_surface',
'Temperature_altitude_above_msl',
'Temperature_height_above_ground',
'Temperature_high_cloud_top_Mixed_intervals_Average',
'Temperature_isobaric',
'Temperature_low_cloud_top_Mixed_intervals_Average',
'Temperature_maximum_wind',
'Temperature_middle_cloud_top_Mixed_intervals_Average',
'Temperature_potential_vorticity_surface',
'Temperature_pressure_difference_layer',
'Temperature_sigma',
'Temperature_surface',
'Temperature_tropopause',
'Total_cloud_cover_boundary_layer_cloud_Mixed_intervals_Average',
'Total_cloud_cover_convective_cloud',
'Total_cloud_cover_entire_atmosphere',
'Total_cloud_cover_entire_atmosphere_Mixed_intervals_Average',
'Total_cloud_cover_isobaric',
'Total_ozone_entire_atmosphere_single_layer',
'Total_precipitation_surface_Mixed_intervals_Accumulation',
'U-Component_Storm_Motion_height_above_ground_layer',
'Upward_Long-Wave_Radp_Flux_atmosphere_top_Mixed_intervals_Average',
'Upward_Long-Wave_Radp_Flux_surface_Mixed_intervals_Average',
'Upward_Short-Wave_Radiation_Flux_atmosphere_top_Mixed_intervals_Average',
'Upward_Short-Wave_Radiation_Flux_surface_Mixed_intervals_Average',
'V-Component_Storm_Motion_height_above_ground_layer',
'Vegetation_surface',
'Ventilation_Rate_planetary_boundary',
'Vertical_Speed_Shear_potential_vorticity_surface',
'Vertical_Speed_Shear_tropopause',
'Vertical_velocity_geometric_isobaric',
'Vertical_velocity_pressure_isobaric',
'Vertical_velocity_pressure_sigma',
'Visibility_surface',
'Volumetric_Soil_Moisture_Content_depth_below_surface_layer',
'Water_equivalent_of_accumulated_snow_depth_surface',
'Water_runoff_surface_Mixed_intervals_Accumulation',
'Wilting_Point_surface',
'Wind_speed_gust_surface',
'Zonal_Flux_of_Gravity_Wave_Stress_surface_Mixed_intervals_Average',
'u-component_of_wind_altitude_above_msl',
'u-component_of_wind_height_above_ground',
'u-component_of_wind_isobaric',
'u-component_of_wind_maximum_wind',
'u-component_of_wind_planetary_boundary',
'u-component_of_wind_potential_vorticity_surface',
'u-component_of_wind_pressure_difference_layer',
'u-component_of_wind_sigma',
'u-component_of_wind_tropopause',
'v-component_of_wind_altitude_above_msl',
'v-component_of_wind_height_above_ground',
'v-component_of_wind_isobaric',
'v-component_of_wind_maximum_wind',
'v-component_of_wind_planetary_boundary',
'v-component_of_wind_potential_vorticity_surface',
'v-component_of_wind_pressure_difference_layer',
'v-component_of_wind_sigma',
'v-component_of_wind_tropopause'}
获取绘图需要变量
In :
# Query for Latest GFS Run
now = datetime.utcnow()
query = ncss.query()
query.lonlat_box(north=50, south=20, east=130, west=100).time((datetime(2024, 2, 18, 18)))
query.accept('netcdf4')
query.variables('Geopotential_height_isobaric', 'u-component_of_wind_isobaric',
            'v-component_of_wind_isobaric')
data =ncss.get_data(query)
数据处理
In :
lon = data.variables['longitude'][:]
lat = data.variables['latitude'][:]

times = data.variables.dimensions]
vtime = num2date(times[:], units=times.units)

lev_500 = np.where(data.variables['isobaric'][:] == 50000)

hght_500 = data.variables['Geopotential_height_isobaric']
hght_500 = ndimage.gaussian_filter(hght_500, sigma=3, order=0) * units.meter

uwnd_500 = units('m/s') * data.variables['u-component_of_wind_isobaric']
vwnd_500 = units('m/s') * data.variables['v-component_of_wind_isobaric']
绘图部分
In :
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
fig = plt.figure(figsize=(15, 12))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())

# Plot Titles
plt.title(r'500-hPa Heights (m)', loc='left')
plt.title('VALID: {}'.format(vtime), loc='right')

# Plot Background
ax.set_extent(, ccrs.PlateCarree())
ax.coastlines('50m', edgecolor='black', linewidth=0.75)
ax.add_feature(cfeature.STATES, linewidth=0.5)

# Plot Height Contours
clev500 = np.arange(5100, 6061, 60)
cs = ax.contour(lon, lat, hght_500.m, clev500, colors='black', linewidths=2, linestyles='solid', transform=ccrs.PlateCarree())
plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True)

for t in cs.labelTexts:
    t.set_bbox({'fc': 'w'})

cf = ax.contourf(lon, lat, hght_500.m, clev500, extend='both', cmap='bwr', transform=ccrs.PlateCarree())
cb = plt.colorbar(cf, orientation='vertical', extendrect=True, ticks=clev500)
# Plot Wind Barbs
ax.barbs(lon, lat, uwnd_500.m, vwnd_500.m, length=6, regrid_shape=25,pivot='middle', transform=ccrs.PlateCarree())
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='gray', alpha=0.5, linestyle='--')

gl.xlabels_top = False
gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
plt.show()

/opt/conda/lib/python3.9/site-packages/cartopy/mpl/gridliner.py:451: UserWarning: The .xlabels_top attribute is deprecated. Please use .top_labels to toggle visibility instead.
warnings.warn('The .xlabels_top attribute is deprecated. Please '
/opt/conda/lib/python3.9/site-packages/cartopy/mpl/gridliner.py:487: UserWarning: The .ylabels_right attribute is deprecated. Please use .right_labels to toggle visibility instead.
warnings.warn('The .ylabels_right attribute is deprecated. Please '





文章来源于公众号:气python风雨

页: [1]
查看完整版本: matplotlib:怎么画带白色框的等值线