Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fixing filling for feasible region

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

enter image description here

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()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading