I’m trying to correct the filling for a feasible region using Python’s matplotlib
These are the inequalities:
x = np.linspace(0, 2000, 1000)
y1 = (3600 - 3*x) / 5
y2 = (1600 - x) / 2
y3 = (48000 - 50*x) / 20
I only care about the feasible region but I can’t get the constraints right
fig, ax = plt.subplots()
ax.plot(x, y1, label='3x+5y<=3600')
ax.plot(x, y2, label='x+2y<=1600')
ax.plot(x, y3, label='50x+20y<=48000')
ax.fill_between(x, 0, y3, where=(y1<= (3600-3*x)/5) & (y2<= (1600-x)/2) & (y3<= (48000-50*x)/20), alpha=0.2)
# plot the vertices
for vertex in vertices:
ax.plot(vertex[0], vertex[1], 'ro')
plt.xlim(xmin=0)
plt.ylim(ymin=0)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Feasible Region')
plt.legend()
plt.show()
As you can notice the feasible region is not filled correctly, although the logic seems fine to me.
How to fix the fill_between parameters so it would fill it correctly?
>Solution :
Instead of using the fill_between method, use the fill method to correctly fill the feasible region.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2000, 1000)
# Define the inequalities for each constraint
y1 = (3600 - 3*x) / 5
y2 = (1600 - x) / 2
y3 = (48000 - 50*x) / 20
# Find the vertices of the feasible region
vertices = []
for i in range(len(x)):
if y1[i] >= 0 and y2[i] >= 0 and y3[i] >= 0:
vertices.append((x[i], min(y1[i], y2[i], y3[i])))
# Plot the constraints
plt.plot(x, y1, label='3x+5y<=3600')
plt.plot(x, y2, label='x+2y<=1600')
plt.plot(x, y3, label='50x+20y<=48000')
# Plot the feasible region
vertices.append((0, 0)) # Add the origin as a vertex
vertices.sort()
x_coords, y_coords = zip(*vertices)
plt.fill(x_coords, y_coords, 'b', alpha=0.2)
# plot the vertices
for vertex in vertices:
plt.plot(vertex[0], vertex[1], 'ro')
plt.xlim(xmin=0)
plt.ylim(ymin=0)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Feasible Region')
plt.legend()
plt.grid(True)
plt.show()

