2013-07-10 144 views
5

如何使用matplotlib繪製由一些線性不等式函數限定的區域。Python Matplotlib:繪製線性不等式函數

例如,如果我們有3個功能: Ŷ< = -2 + 4X,Y> = 2 + 0.5×,Y < = 7 -0.3x

我要提請事端simmilar如鎢alpha的確如下:http://www3.wolframalpha.com/Calculate/MSP/MSP43251aca1dfd6ebcd862000067b9fd36a79h3igf?MSPStoreType=image/gif&s=39&w=200.&h=210.&cdf=Coordinates&cdf=Tooltips

+2

那麼,你嘗試過什麼?你看過畫廊嗎?我認爲'fill_between'會讓你做你想做的事情http://matplotlib.org/examples/pylab_examples/fill_between_demo.html – tacaswell

回答

10

我寫了一個非常簡單的例子,只對你的問題有效,但很容易擴展和概括它。唯一的竅門是使用simpy來簡化找到構建所需多邊形的根的問題。 (來自http://docs.sympy.org/dev/modules/solvers/solvers.html兩者)​​

import numpy as np 
import matplotlib.pyplot as plt 
from sympy.solvers import solve 
from sympy import Symbol 

def f1(x): 
    return 4.0*x-2.0 
def f2(x): 
    return 0.5*x+2.0 
def f3(x): 
    return -0.3*x+7.0 

x = Symbol('x') 
x1, = solve(f1(x)-f2(x)) 
x2, = solve(f1(x)-f3(x)) 
x3, = solve(f2(x)-f3(x)) 

y1 = f1(x1) 
y2 = f1(x2) 
y3 = f2(x3) 

plt.plot(x1,f1(x1),'go',markersize=10) 
plt.plot(x2,f1(x2),'go',markersize=10) 
plt.plot(x3,f2(x3),'go',markersize=10) 

plt.fill([x1,x2,x3,x1],[y1,y2,y3,y1],'red',alpha=0.5) 

xr = np.linspace(0.5,7.5,100) 
y1r = f1(xr) 
y2r = f2(xr) 
y3r = f3(xr) 

plt.plot(xr,y1r,'k--') 
plt.plot(xr,y2r,'k--') 
plt.plot(xr,y3r,'k--') 

plt.xlim(0.5,7) 
plt.ylim(2,8) 

plt.show() 

enter image description here

問候

+0

謝謝,這正是我需要的:) – N10