如何将Matplotlib contourf填充图案(Hatch)改为黑色而非白色
contourf填充图案无法改为黑色的解决办法
问题背景
尝试用contourf的填充图案在SST异常图上叠加显著性掩码,无论调整edgecolor、facecolor等参数,或是切换contourf/contour写法,填充图案始终显示为白色,无法改为黑色。
原代码片段
import matplotlib.pyplot as plt import numpy as np import seaborn as sns import cartopy.crs as ccrs from cartopy.feature import NaturalEarthFeature all_plots = [] plt.rcParams.update({'hatch.color': 'k'}) land = NaturalEarthFeature('physical', 'land', '50m', edgecolor='face', facecolor='white') # Create a 2x2 subplot (2 rows, 2 columns) for 4 plots, with Miller projection fig, axs = plt.subplots(2, 2, figsize=(18, 9), subplot_kw={'projection': ccrs.Miller()}) plt.subplots_adjust(hspace=0.25, wspace=0.1) # Adjust spacing # Shared colorbar arguments cmap = 'RdBu_r' # Function to set up common gridlines and features def setup_ax(ax, title): ax.coastlines(zorder=2) ax.add_feature(land, zorder=1) ax.set_extent([-180, 180, -1, 90], crs=ccrs.PlateCarree()) # Limit y-axis to 0-90 degrees gl = ax.gridlines(draw_labels=True, linewidth=0.6, zorder=1, color='dimgray', alpha=0.3) gl.left_labels = True gl.bottom_labels = True gl.top_labels = False gl.right_labels = False gl.xlabel_style = {'size': 10} gl.ylabel_style = {'size': 10} gl.ylocator = plt.FixedLocator(np.arange(0, 91, 20)) # Add y-axis gridlines at 0°, 20°, 40°, etc. gl.xlocator = plt.FixedLocator(np.arange(-180, 181, 60)) # Optional: adjust x-axis labels ax.set_title(title, fontsize=15) # Plot 1: Strongest months of hailseason (May-August) im = mean_sst_strongest_months_north.plot(ax=axs[0, 0], cmap=cmap, add_colorbar=False, vmin=vmin, vmax=vmax, transform=ccrs.PlateCarree()) # Overlay the significance mask for the first plot cax1 = axs[0, 0].contourf(significant_mask_months_strongest_north.longitude, significant_mask_months_strongest_north.latitude, significant_mask_months_strongest_north, levels=[0.5, 1], colors='none', hatches=['oo'], transform=ccrs.PlateCarree()) setup_ax(axs[0, 0], 'Strongest months of hailseason (May-Aug)') for ax in axs.flat: rect = Rectangle((5.5, 45.3), 5.4, 2.7, linewidth=1.5, edgecolor='limegreen', facecolor='none', transform=ccrs.PlateCarree()) ax.add_patch(rect) [... other 3 plots] # Add a shared colorbar at the bottom cbar = fig.colorbar(im, ax=axs, pad=0.06, orientation="horizontal", shrink=0.7, extend="both", aspect=50) cbar.set_label('SST anomalies [K]', fontsize=15) # Add a main title for the figure fig.suptitle('Mean SST anomalies of 10 strongest hailyears in northern Switzerland', fontsize=18, y=0.97) # Save the plot to the specified directory plt.savefig("/sst_strongest_4periods_north_significance_95.jpeg", dpi=350, bbox_inches='tight', pad_inches=0.05) # Close all open plots plt.close('all')
当前效果
显著性区域的填充图案显示为白色,与背景难以区分,无法达到预期的黑色掩码效果。
解决方法
核心修改
在contourf调用中显式指定edgecolor='k'——当设置colors='none'时,填充图案的颜色会继承edgecolor的默认值(白色),覆盖你全局设置的hatch.color。修改后的代码如下:
cax1 = axs[0, 0].contourf(significant_mask_months_strongest_north.longitude, significant_mask_months_strongest_north.latitude, significant_mask_months_strongest_north, levels=[0.5, 1], colors='none', hatches=['oo'], edgecolor='k', # 新增edgecolor参数 transform=ccrs.PlateCarree())
可选优化
- 若不想全局设置
hatch.color,可以直接在contourf中用hatchcolor='k'单独指定(需matplotlib 3.3及以上版本) - 添加
zorder=3参数,确保掩码图案显示在SST图层上方:
cax1 = axs[0, 0].contourf(..., zorder=3)
内容的提问来源于stack exchange,提问作者Lena
相关产品推荐
相关产品推荐

