使用 fill_between 和 min/max 表示不等式
Using fill_between and min/max to represent inequalities
我的代码:
import matplotlib.pyplot as plt
import numpy as np
# x > 0
x = np.linspace(0,17, 100)
#x2>=0
y0 = (x*0)
#-x1+x2 <= 1
y1 = 1+x
#x1+6x2 <= 15
y2 = 15/6 - (1/6)*x
#4x1-x2 <= 10
y3 = 4*x-10
plt.xlabel(r'$x_2>=0$')
plt.ylabel(r'$x_1>=0$')
plt.plot(x,y0,'r')
plt.plot(x,y1, 'b')
plt.plot(x,y2, 'y')
plt.plot(x,y3, 'g')
plt.xlim((0,17))
plt.ylim((0,9))
#feasible region
a1 = np.minimum(y2,y3)
a2 = np.minimum(y1,y2)
plt.fill_between(x, y1, y3, where = a1 < a2, color = 'grey', alpha = 0.5)
这会生成以下图:
但是,我不希望灰色延伸超过黄线,即我想删除位于 4 边形多边形上方的三角形内部的灰色。意思是,我希望也删除超过黄线的值,但我不确定如何在不向 where
添加另一个参数的情况下表示这一点。尝试此操作时我只遇到错误。有没有办法为 where
指定多个参数?
编辑:我已通过将参数调整为:
解决了问题
#feasible region
a1 = np.maximum(y0,y3)
a2 = np.minimum(y1,y2)
plt.fill_between(x, a1, a2, where = a1 < a2, color = 'grey', alpha = 0.5)
但是,我仍然对可能为 where
指定多个参数感到好奇,所以我会留下这个问题。
您可以使用 np.maxiumum
和 np.minimum
来定义您的 y-values。这样你就不必“piece-wise”了。在您的下限上使用 maximum
来定义一个下限来绘制。与 minimum
和您的上限相同。另外,在你的例子中,你切断了 y 轴,你实际上在下面有阴影区域。
Y1 = np.maximum(y0, y3)
Y2 = np.minimum(y1, y2)
plt.fill_between(x, Y1, Y2, where = Y1 < Y2, color = 'grey', alpha = 0.5)
我的代码:
import matplotlib.pyplot as plt
import numpy as np
# x > 0
x = np.linspace(0,17, 100)
#x2>=0
y0 = (x*0)
#-x1+x2 <= 1
y1 = 1+x
#x1+6x2 <= 15
y2 = 15/6 - (1/6)*x
#4x1-x2 <= 10
y3 = 4*x-10
plt.xlabel(r'$x_2>=0$')
plt.ylabel(r'$x_1>=0$')
plt.plot(x,y0,'r')
plt.plot(x,y1, 'b')
plt.plot(x,y2, 'y')
plt.plot(x,y3, 'g')
plt.xlim((0,17))
plt.ylim((0,9))
#feasible region
a1 = np.minimum(y2,y3)
a2 = np.minimum(y1,y2)
plt.fill_between(x, y1, y3, where = a1 < a2, color = 'grey', alpha = 0.5)
这会生成以下图:
但是,我不希望灰色延伸超过黄线,即我想删除位于 4 边形多边形上方的三角形内部的灰色。意思是,我希望也删除超过黄线的值,但我不确定如何在不向 where
添加另一个参数的情况下表示这一点。尝试此操作时我只遇到错误。有没有办法为 where
指定多个参数?
编辑:我已通过将参数调整为:
解决了问题#feasible region
a1 = np.maximum(y0,y3)
a2 = np.minimum(y1,y2)
plt.fill_between(x, a1, a2, where = a1 < a2, color = 'grey', alpha = 0.5)
但是,我仍然对可能为 where
指定多个参数感到好奇,所以我会留下这个问题。
您可以使用 np.maxiumum
和 np.minimum
来定义您的 y-values。这样你就不必“piece-wise”了。在您的下限上使用 maximum
来定义一个下限来绘制。与 minimum
和您的上限相同。另外,在你的例子中,你切断了 y 轴,你实际上在下面有阴影区域。
Y1 = np.maximum(y0, y3)
Y2 = np.minimum(y1, y2)
plt.fill_between(x, Y1, Y2, where = Y1 < Y2, color = 'grey', alpha = 0.5)