如何在Matplotlib中填充含不相交曲线的两条等高线间区域?
解决两条等高线间区域的填充问题
方法一:用contourf直接填充(推荐)
这是最简便高效的方式,contourf专门用来填充等高线之间的区域,完全适配你的场景。只需要指定要填充的数值区间,它会自动识别两条等高线围成的区域并填充。
修改后的代码:
import numpy as np from numpy import apply_along_axis, meshgrid, arange, vstack import matplotlib.pyplot as plt # 定义目标函数 f = lambda x: x[1]**2 + 3*(x[0]**2)*(x[0]**2 - 1) f_broadcasted = lambda x: apply_along_axis(f, 1, x) # 生成网格数据 xlims, ylims = [-2, 2], [-2, 2] x, y = meshgrid(arange(*xlims, 0.005), arange(*ylims, 0.005)) xys = vstack((x.flatten(), y.flatten())).T z = f_broadcasted(xys).reshape(x.shape) fig, ax = plt.subplots() # 填充-0.02到0.02之间的区域,设置填充色和透明度 ax.contourf(x, y, z, levels=[-0.02, 0.02], colors=['lightblue'], alpha=0.5) # 叠加原来的等高线线条,保证边界清晰 contours = ax.contour(x, y, z, levels=[-0.02, 0.02], colors=['forestgreen', 'royalblue']) plt.show()
这里contourf的levels参数传入[-0.02, 0.02],就会自动填充z值在这两个数之间的所有区域,不管等高线是单条还是多条,都能正确识别闭合区域,不需要手动处理路径问题。
方法二:手动处理等高线路径填充(按需使用)
如果需要更精细控制填充范围(比如只填充某一段围成的区域),可以提取等高线的路径,手动合并成闭合区域后填充。
代码示例:
import numpy as np from numpy import apply_along_axis, meshgrid, arange, vstack import matplotlib.pyplot as plt from matplotlib.path import Path from matplotlib.patches import PathPatch # 定义目标函数 f = lambda x: x[1]**2 + 3*(x[0]**2)*(x[0]**2 - 1) f_broadcasted = lambda x: apply_along_axis(f, 1, x) # 生成网格数据 xlims, ylims = [-2, 2], [-2, 2] x, y = meshgrid(arange(*xlims, 0.005), arange(*ylims, 0.005)) xys = vstack((x.flatten(), y.flatten())).T z = f_broadcasted(xys).reshape(x.shape) fig, ax = plt.subplots() contours = ax.contour(x, y, z, levels=[-0.02, 0.02], colors=['forestgreen', 'royalblue']) # 获取两条等高线的路径:第一条是level=-0.02的单曲线,第二条是level=0.02的双曲线 single_path = contours.collections[0].get_paths()[0] double_paths = contours.collections[1].get_paths() # 逐个填充单曲线和每条双曲线围成的区域 for dp in double_paths: # 合并路径:把单曲线和反向的双曲线拼接,形成闭合区域 vertices = np.concatenate([single_path.vertices, dp.vertices[::-1]]) codes = np.concatenate([single_path.codes, dp.codes[::-1]]) closed_path = Path(vertices, codes) # 创建填充补丁并添加到坐标轴 patch = PathPatch(closed_path, facecolor='lightblue', alpha=0.5) ax.add_patch(patch) plt.show()
这个方法通过提取等高线的路径数据,手动拼接成闭合的路径,再用PathPatch实现填充,适合需要定制填充区域的场景。
内容的提问来源于stack exchange,提问作者Physics_Student
相关产品推荐
相关产品推荐

