在两条以上的曲线之间填充matplotlib

时间:2020-09-15 04:37:08

标签: python matplotlib

我想在以下问题中填写3行。这是代码:

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

我想在下图中用红色阴影填充(在y1,y2,y3和零之间)enter image description here

2 个答案:

答案 0 :(得分:3)

您可以在零到三个曲线的最小值之间填充:

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

resulting plot

答案 1 :(得分:2)

请注意:

  1. np.vstack([y1, y2, y3])根据您的3个“ y”数组创建一个3行数组。

  2. ….min(0)计算每列的最小值,因此实际上 至少3个源数组(对于更高的 x 也是负值)。

  3. ….clip(min=0)将上述否定元素转换为 0

因此添加到您的代码中:

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

例如在您的第一个 fill_between 之后。

为了您的数据,并添加上面说明的代码,我得到了:

enter image description here

如果需要,可以将填充颜色更改为适合您需要的颜色。