rellenar entre más de dos curvas matplotlib

Sep 15 2020

Quiero completar entre 3 líneas en el siguiente problema. Aquí está el código:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

# Construct lines
# x > 0
x = np.linspace(0, 20, 2000)
# C1
y1 = (36-2*x)/6
# C2
y2 = (30-5*x)/3
# C3
y3 = (40-8*x)/2
# C4
# y4 = 0*x

# Make plot
plt.plot(x, y1, label=r'$2 x_{1} + 6 x_{2}\leq 36$')
plt.plot(x, y2, label=r'$x_{1} + 3 x_{2}\leq 30$')
plt.plot(x, y3, label=r'$x_{1} + 2 x_{2}\leq 40$')
# plt.plot(x, y4, label=r'$x_{1}, x_{2}\geq 0$')
plt.xlim((0, 16))
plt.ylim((0, 11))
plt.xlabel(r'$x_1$')
plt.ylabel(r'$x_2$')

# Fill feasible region
y5 = np.minimum(0, 0)
y6 = np.maximum(y2, y3)
plt.fill_between(x, y1, y2, color='grey', alpha=0.5,
                interpolate=True)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

Me gustaría rellenar lo que está rayado en rojo en la imagen de abajo (entre y1, y2, y3 y cero)

Respuestas

3 JohanC Sep 15 2020 at 13:28

Puede completar entre cero y el mínimo de las tres curvas:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 2000)
y1 = (36 - 2 * x) / 6
y2 = (30 - 5 * x) / 3
y3 = (40 - 8 * x) / 2

plt.plot(x, y1, label=r'$2 x_{1} + 6 x_{2}\leq 36$')
plt.plot(x, y2, label=r'$x_{1} + 3 x_{2}\leq 30$')
plt.plot(x, y3, label=r'$x_{1} + 2 x_{2}\leq 40$')
plt.xlim((0, 16))
plt.ylim((0, 11))
plt.xlabel(r'$x_1$')
plt.ylabel(r'$x_2$')

plt.fill_between(x, y1, y2, color='grey', alpha=0.5,
                 interpolate=True)
plt.fill_between(x, 0, np.min([y1, y2, y3], axis=0), color='red', alpha=0.5, hatch='//',
                 interpolate=True, label='$intersection$')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.tight_layout()
plt.show()

2 Valdi_Bo Sep 15 2020 at 14:11

Tenga en cuenta que:

  1. np.vstack([y1, y2, y3]) crea una matriz de 3 filas a partir de sus matrices de 3 "y".

  2. ….min(0)calcula el mínimo a lo largo de cada columna, por lo que en realidad es un mínimo de sus 3 matrices de origen (también con valores negativos para x superior ).

  3. ….clip(min=0)transforma los elementos negativos anteriores en 0 .

Así que agregue a su código:

plt.fill_between(x, 0, np.vstack([y1, y2, y3]).min(0).clip(min=0),
    color='yellow', alpha=0.5, interpolate=True)

por ejemplo, después de su primer fill_between .

Para sus datos y el código con la instrucción anterior agregada, obtuve:

Si lo desea, cambie el color de relleno al que se adapte a sus necesidades.