如何在Matplotlib同一画布绘制不同hatch属性的contourf图
Matplotlib contourf Hatch局部自定义方案
不用依赖全局
plt.rcParams,直接操作contourf返回的对象就能实现局部hatch属性设置:- 调用
contourf时先指定hatch样式(比如///、\\\\\\这类符号) - 遍历返回集合里的每个填充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
相关产品推荐
相关产品推荐

