Python绘制优化解空间的轮廓图
在说明优化问题的解空间时等高线绘图特别方便。axes.Axes.contour不仅可以用来表示目标函数的地形还可以用来生成约束函数的边界曲线。可以使用TickedStroke绘制约束线以区分约束边界的有效侧和无效侧。axes.Axes.contour生成的曲线左侧数值较大。角度参数以零点为基准向左递增。因此在使用TickedStroke说明典型优化问题中的约束时角度应设置在零到180度之间。import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import patheffectsfig, ax plt.subplots(figsize(6, 6))nx 101ny 105# 设置调查向量xvec np.linspace(0.001, 4.0, nx)yvec np.linspace(0.001, 4.0, ny)# Set up survey matrices. Design disk loading and gear ratio.x1, x2 np.meshgrid(xvec, yvec)# 评估一些东西以绘图obj x1**2 x2**2 - 2*x1 - 2*x2 2g1 -(3*x1 x2 - 5.5)g2 -(x1 2*x2 - 4.5)g3 0.8 x1**-3 - x2cntr ax.contour(x1, x2, obj, [0.01, 0.1, 0.5, 1, 2, 4, 8, 16],colorsblack)ax.clabel(cntr, fmt%2.1f, use_clabeltextTrue)cg1 ax.contour(x1, x2, g1, [0], colorssandybrown)cg1.set(path_effects[patheffects.withTickedStroke(angle135)])cg2 ax.contour(x1, x2, g2, [0], colorsorangered)cg2.set(path_effects[patheffects.withTickedStroke(angle60, length2)])cg3 ax.contour(x1, x2, g3, [0], colorsmediumblue)cg3.set(path_effects[patheffects.withTickedStroke(spacing7)])ax.set_xlim(0, 4)ax.set_ylim(0, 4)plt.show()参考文献https://matplotlib.org/stable/gallery/images_contours_and_fields/contours_in_optimization_demo.html