gpt4 book ai didi

Python:Matplotlib 中 LP 的可行区域和目标函数的优雅可视化?

转载 作者:太空宇宙 更新时间:2023-11-03 15:09:59 26 4
gpt4 key购买 nike

我想学习绘制以下LP问题here优雅地使用 matplotlib

1*x[1] + 2x[2] -> max

1*x[1] + 0*x[2] <= 5
0*x[1] + 1*x[2] <= 5
1*x[1] + 0*x[2] >= 1
0*x[1] + 1*x[2] >= 1
1*x[1] + 1*x[2] <= 6

其中第一行是目标函数,其余是 LP 问题的约束。

我已经找到了一个演示here我稍微调整了一下,但如何优雅地做到这一点?如何用线条将图片中的上三角填充为灰色(不是像演示中那样的功能)?

如何在Python的Matplotlib中优雅地可视化LP(线性规划)问题的目标函数和可行区域?

<小时/>

代码

import numpy as np, matplotlib.pyplot as plt
#I hold x a line while defining new values for each y
x = np.linspace(0, 20, 2000)
#1*x[1] + 0*x[2] <= 5
#y0*0=5-x #No initialization with respect to y0 because it is zero.
#0*x[1] + 1*x[2] <= 5
y1=5+x*0
#1*x[1] + 0*x[2] >= 1
#y2*0=1-x #No inititialization
#0*x[1] + 1*x[2] >= 1
y3=1-x*0
#1*x[1] + 1*x[2] <= 6
y4=6-x
#TODO: HOW TO DRAW THE ABOVE LINEAR EQUATIONS ELEGANTLY in matplotlib?
#Drawing the lines by end points because of the zeroes.
plt.plot(x,y4,label=r'$x[1]+x[2]<=6$')
plt.plot([5,5],[10,-10]) #x < 5
plt.plot([10,-2],[5,5]) #y2 < 5
plt.plot([1,1],[10,-10], 'r-') #x >= 1
plt.plot([10,-2],[1,1],'b--') #y3 >= 1
#TODO: how to fill the upper triangle only?
# http://benalexkeen.com/linear-programming-with-python-and-pulp-part-1/
#plt.fill_between(x, y5, y6, where=y5>y6, color='grey', alpha=0.5)
plt.show()

enter image description here

最佳答案

我可以建议以下内容,其中尽可能使用 xy{i}

import numpy as np, matplotlib.pyplot as plt
#I hold x a line while defining new values for each y
x = np.linspace(0, 20, 2000)
#1*x[1] + 0*x[2] <= 5
#y0*0=5-x #No initialization with respect to y0 because it is zero.
#0*x[1] + 1*x[2] <= 5
y1=5+x*0
#1*x[1] + 0*x[2] >= 1
#y2*0=1-x #No inititialization
#0*x[1] + 1*x[2] >= 1
y3=1-x*0
#1*x[1] + 1*x[2] <= 6
y4=6-x

plt.plot(x,y4,label=r'$x[1]+x[2]<=6$')
plt.plot(x,y1)
plt.axvline(5, color='g') #y2 < 5
plt.axvline(1, color='r') #x >= 1
plt.plot(x,y3,'b--') #y3 >= 1

plt.fill_between(x, y1, y4, where=(x>1)&(x<5), color='grey', alpha=0.5)
plt.show()

enter image description here

我认为 matplotlib 中的任何实现都需要手动求解 x 或 y 各自的不等式,然后绘制相应的图。

关于Python:Matplotlib 中 LP 的可行区域和目标函数的优雅可视化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44293977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com