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

时间:2017-05-31 20:19:15

标签: python matplotlib linear-programming

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

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

2 个答案:

答案 0 :(得分:1)

我可以建议以下内容,尽可能使用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的相应不等式,然后执行相应的绘图。

答案 1 :(得分:0)

您应该可以使用GrUMPy执行此操作。但是,设置和使用并不是太简单。