python - Metpy: Plotting snowfall analysis but issue with colormap - Stack Overflow

admin2025-04-29  2

The plot I made for snowfall analysis looks good but when I plot the colorbar, for some reason it skips over the second to last color and using the extend = 'max' function, it only plots the last color on the colormap for the last two intervals on the colorbar.

I tried using cmap.set_over but am I still getting the same results.

Dataset: Snowfall Dataset

from datetime import datetime

import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import xarray as xr
import numpy as np
import metpy.calc as mpcalc
import netCDF4
from netCDF4 import Dataset
from metpy.units import units
from scipy.ndimage import gaussian_filter
import scipy.ndimage as ndimage
import matplotlib.colors as mcolors
from metpy.plots import USCOUNTIES
from herbie import Herbie, paint
from herbie.toolbox import EasyMap, pc

snowdata = xr.open_dataset('sfav2_CONUS_48h_2025010612.nc')


lat = snowdata['lat'][:].squeeze()
lon = snowdata['lon'][:].squeeze()
snow = snowdata['Data'][:].squeeze()
lon_2d, lat_2d = np.meshgrid(lon, lat)

snowin = snow*39.37

nws_snowfall_colors = [
        "#ffffff",# 0 inches (white)
        "#daeef5", # 0.1 inches
         "#bdd7e7", # 1 inch
         "#6baed6", # 2 inches
         "#08519c", # 3 inches
         "#082694", # 4 inches
         "#ffff96", # 6 inches
         "#ffc400", # 8 inches
         "#ff8700", # 12 inches
        "#db1400", # 18 inches
        "#9e0000", # 24 inches
        "#690000", # 30 inches
         "#360000", # 36 inches
 ]
       # Define the corresponding snowfall values (in inches)
nws_snowfall_cmap = mcolors.ListedColormap(nws_snowfall_colors)

clev_snowfall =  np.concatenate((np.arange(0, .1, .1), np.arange(.1, 1, .9), np.arange(1, 4, 1), np.arange(4, 8, 2), np.arange(8,12,4), np.arange(12,18,6), np.arange(18,24,6), np.arange(24,30,6), np.arange(30,36,6), np.arange(36,42,6)))
norm = mcolors.BoundaryNorm(clev_snowfall, 13)
#nws_snowfall_cmap.set_under("#ffffff")
#nws_snowfall_cmap.set_over("#360000")

datacrs = ccrs.PlateCarree()
plotcrs = ccrs.LambertConformal(central_latitude=35, central_longitude=-100,standard_parallels=(30, 60))
bounds = ([-110, -85, 33, 43])
fig = plt.figure(figsize=(14,12))
ax = fig.add_subplot(1,1,1, projection=plotcrs)
ax.set_extent(bounds, crs=ccrs.PlateCarree())
ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth = 0.75)
ax.add_feature(cfeature.STATES, linewidth = 2)
ax.add_feature(USCOUNTIES, edgecolor='black', linewidth = 1)
cf = ax.contourf(lon_2d, lat_2d, snowin, clev_snowfall, cmap = nws_snowfall_cmap, norm=norm, extend='max', transform=datacrs)
cb = plt.colorbar(cf, orientation='horizontal', ticks = [0, .1, 1, 2, 3, 4, 6, 8, 12, 18, 24, 30, 36])

colorbar: Colorbar

plot: snowfall plot

转载请注明原文地址:http://anycun.com/QandA/1745936071a91350.html