Is it possible to draw linear inequalities and shade the suitable region using python?
I've tried following the answer and code in these questions, but it didn't go well:
Python Matplotlib: Drawing linear inequality functions
My equations are:
x y <= 300
(y/7) >= (x/8)
x >= 0
y >= 0
I have gone this far in the code:
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
# plot the feasible region
d = np.linspace(0,400)
x,y = np.meshgrid(d,d)
plt.imshow( ((y>=0) & (y>=7*x/8) & (x y<=300) & (x>=0)).astype(int) ,
extent=(x.min(),x.max(),y.min(),y.max()),origin="lower", cmap="Greys", alpha = 0.3);
# plot the lines defining the constraints
x = np.linspace(0, 600, 2000)
# y >= 0
y1 = (x*0)
# 2y <= 25 - x
y2 = (7*x)/ 8
# 4y >= 2x - 8
y3 = (300 - x)
# y <= 2x - 5
y4 = 600
l2 = r'$x/7\geqx/8$'
# Make plot
plt.plot(x, y1, label=r'$y\geq0$')
plt.plot(x, y2)
plt.plot(x, y3, label=r'$x y\leq300$')
#plt.plot(x, y4, label=r'$x\geq0')
plt.xlim(0,16)
plt.ylim(0,11)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')`enter code here`
plt.show()
CodePudding user response:
You almost have it! Here are a couple of small changes that should make your code work:
- Increase the precision in
d = np.linspace
.
d = np.linspace(0,400) ---> d = np.linspace(0,400,2000)
- Zoom out. Change your x- and y-limits to something bigger.
plt.xlim(-10,300) and plt.ylim(-10,300)
That should fix the problems you are having!