You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中为contourf图的Xarray数据添加显著性点绘?

问题描述

需要为Xarray DataArray格式的经纬度网格二维气候数据添加点绘(stippling)标识显著性,计划用True/False掩码叠加在变量可视化图上。使用contourf的hatching功能尝试实现时,出现两个问题:点绘覆盖整个绘图区域,且掩码的0、1值以实心色块显示,遮挡了原始变量数据。参考资料设置levels参数仍未解决问题,示例代码及效果如下:

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

def f(x, y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)

x = np.linspace(0, 5, 51)
y = np.linspace(0, 5, 41)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

da = xr.DataArray(Z, coords = {"lon":x, "lat":y}, dims=["lat", "lon"])

fig =plt.figure(figsize=(12, 6))
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

ax1.contourf(da.lon, da.lat, da)

mask = da>0.5
ax2.contourf(da.lon, da.lat, da)
ax2.contourf(da.lon, da.lat, mask, hatches=["."])

效果说明:左图为目标变量的contourf可视化结果,右图为尝试添加点绘后的错误效果——点绘覆盖全图,且掩码的实心色块遮挡了原始数据。

解决方案

问题根源在于contourf默认会将掩码的0(False)和1(True)两个值都绘制成实心色块,导致覆盖原始数据。只需通过两个关键参数调整即可实现仅在掩码为True的区域显示点绘:

修改后的代码

import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

def f(x, y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)

x = np.linspace(0, 5, 51)
y = np.linspace(0, 5, 41)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

da = xr.DataArray(Z, coords = {"lon":x, "lat":y}, dims=["lat", "lon"])

fig =plt.figure(figsize=(12, 6))
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

# 绘制原始变量的contourf图
ax1.contourf(da.lon, da.lat, da)

mask = da>0.5
ax2.contourf(da.lon, da.lat, da)
# 仅在掩码为True的区域添加点绘
ax2.contourf(da.lon, da.lat, mask, 
             levels=[0.5, 1.5],  # 选中值为1(True)的区域
             facecolor='none',   # 取消实心色块,避免遮挡原始数据
             hatches=["."])      # 设置点绘样式

plt.show()

关键参数说明

  • levels=[0.5, 1.5]:由于布尔掩码中True对应1,False对应0,该区间会精准选中所有值大于0.5的区域(即掩码为True的部分),忽略False区域。
  • facecolor='none':关闭contourf的实心填充色,只保留hatch(点绘)样式,完全避免遮挡下方的原始变量可视化结果。
  • hatches=["."]:指定点绘的样式,可根据需求更换为"x"、"+"等其他样式。

内容的提问来源于stack exchange,提问作者Gen Tolhurst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 10:35:12