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

如何在Matplotlib同一画布绘制不同hatch属性的contourf图

Matplotlib contourf Hatch局部自定义方案
  • 不用依赖全局plt.rcParams,直接操作contourf返回的对象就能实现局部hatch属性设置:

    1. 调用contourf时先指定hatch样式(比如///、\\\\\\这类符号)
    2. 遍历返回集合里的每个填充patch,单独设置它的edgecolor(hatch颜色)和linewidth(hatch线宽)
  • 完整示例代码:

import matplotlib.pyplot as plt
import numpy as np

# 生成测试数据
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(X**2 + Y**2))
Z2 = np.exp(-((X-1)**2 + (Y-1)**2))
Z = Z1 - Z2

fig, ax = plt.subplots()

# 第一个contourf:绿色细线hatch
cs1 = ax.contourf(X, Y, Z, levels=np.linspace(-0.8, 0, 4), hatches=['///']*3, alpha=0.5)
for patch in cs1.collections:
    patch.set_edgecolor('green')
    patch.set_linewidth(0.5)

# 第二个contourf:蓝色粗线hatch
cs2 = ax.contourf(X, Y, Z, levels=np.linspace(0, 0.8, 4), hatches=['\\\\\\']*3, alpha=0.5)
for patch in cs2.collections:
    patch.set_edgecolor('blue')
    patch.set_linewidth(2)

plt.colorbar(cs2)
plt.show()
  • 注意点:
    • hatches参数的列表长度要和levels划分的区间数对应(比如levels有4个值,对应3个区间,所以hatches要给3个元素)
    • 每个contourf的patch集合是独立的,修改其中一个不会影响另一个,完全避开全局配置

内容的提问来源于stack exchange,提问作者Paweł Korzeb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:17:13