前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >matplotlib:怎么画带白色框的等值线

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

作者头像
用户11172986
发布2024-06-20 18:15:02
540
发布2024-06-20 18:15:02
举报
文章被收录于专栏:气python风雨气python风雨

前言

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

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

导入库与链接数据库

In [14]:

代码语言:javascript
复制
代码语言:javascript
复制
# 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[0].subset()
代码语言:javascript
复制

In [9]:

代码语言:javascript
复制
代码语言:javascript
复制
ncss.variables
代码语言:javascript
复制

Out[9]:

代码语言:javascript
复制
{'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 [10]:

代码语言:javascript
复制
代码语言:javascript
复制
# 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)
代码语言:javascript
复制

数据处理

In [26]:

代码语言:javascript
复制
代码语言:javascript
复制
lon = data.variables['longitude'][:]
lat = data.variables['latitude'][:]

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

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

hght_500 = data.variables['Geopotential_height_isobaric'][0, lev_500, :, :]
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'][0, lev_500, :, :]
vwnd_500 = units('m/s') * data.variables['v-component_of_wind_isobaric'][0, lev_500, :, :]
代码语言:javascript
复制

绘图部分


In [28]:

代码语言:javascript
复制
代码语言:javascript
复制
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[0]), loc='right')

# Plot Background
ax.set_extent([100., 130., 20., 50.], 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()
代码语言:javascript
复制
代码语言:javascript
复制
/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 '
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-02-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 气python风雨 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 导入库与链接数据库
  • 获取绘图需要变量
  • 数据处理
  • 绘图部分
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档