10

How can I draw an area bounded by some linear inequality functions using matplotlib.

For example, if we have 3 functions: y <= -2+4x, y >= 2+0.5x, y <= 7 -0.3x

I would like to draw something similar as wolfram alpha does: http://www3.wolframalpha.com/Calculate/MSP/MSP43251aca1dfd6ebcd862000067b9fd36a79h3igf?MSPStoreType=image/gif&s=39&w=200.&h=210.&cdf=Coordinates&cdf=Tooltips

Hassan
  • 99
  • 2
  • 7
N10
  • 429
  • 2
  • 4
  • 17
  • 3
    So, what have you tried? Did you look at the gallery? I think `fill_between` will let you do what you want http://matplotlib.org/examples/pylab_examples/fill_between_demo.html – tacaswell Jul 10 '13 at 18:32

1 Answers1

22

I wrote a very simple example, valid for your problem only, but it's easily to extend and generalize it. The only trick is to use simpy to simplify the problem of finding the roots for to build the desired polygon. (Taken from 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

Regards

Pablo
  • 2,443
  • 1
  • 20
  • 32
  • How are you handling greater or less than equal to sign? In other words, how will you write y <= 7 -0.3x and y >= 7 -0.3x? – Vivek Mar 05 '22 at 17:51
  • This solution now leads to: ImportError: SymPy now depends on mpmath as an external library. See https://docs.sympy.org/latest/install.html#mpmath for more information – seeker_after_truth Jul 08 '22 at 18:34