riempire tra più di due curve matplotlib

Sep 15 2020

Voglio riempire tra 3 righe nel seguente problema. Ecco il codice:

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

Vorrei riempire ciò che è tratteggiato in rosso nell'immagine sottostante (tra y1, y2, y3 e zero)

Risposte

3 JohanC Sep 15 2020 at 13:28

Puoi riempire tra zero e il minimo delle tre curve:

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

Nota che:

  1. np.vstack([y1, y2, y3]) crea un array a 3 righe dai tuoi array a 3 "y".

  2. ….min(0)calcola il minimo lungo ogni colonna, quindi in realtà è un minimo dei tuoi 3 array sorgente (anche con valori negativi per x maggiori ).

  3. ….clip(min=0)trasforma gli elementi negativi di cui sopra in 0 .

Quindi aggiungi al tuo codice:

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

es. dopo il tuo primo fill_between .

Per i tuoi dati e il codice con le istruzioni sopra aggiunte, ho ottenuto:

Se lo desideri, cambia il colore di riempimento in base alle tue esigenze.