使用 fill_between 和 min/max 来表示不等式 [英] Using fill_between and min/max to represent inequalities

查看:43
本文介绍了使用 fill_between 和 min/max 来表示不等式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

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 指定多个参数?

However, I do not want the grey to extend past the yellow line, i.e. I want to remove the grey that is located inside the triangle above the 4 sided polygon. Meaning, I want the values that exceed above the yellow line to be removed as well, but I am not sure how to represent this without adding another argument to where. I have only gotten errors when attempting this. Is there a way to specify multiple arguments for where?

我通过调整参数解决了这个问题:

I have solved the problem by tweaking my parameters to:

#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 中指定多个参数感到好奇,因此我将继续讨论该问题.

however, I am still curious about potentially specifying multiple arguments to where, so I will leave the question up.

推荐答案

您可以使用 np.maxiumumnp.minimum 来定义您的 y 值.这样,您就不必逐段"地进行操作了.它.在下限上使用 maximum (最大值)来定义一个要绘制的下限.与 minimum 和你的上限相同.另外,在您的示例中,您切断了y轴,实际上在其下面有阴影区域.

You can use np.maxiumum and np.minimum to define your y-values. This way you don't have to "piece-wise" it. Use maximum on your lower bounds to define just one lower bound to plot. Same with minimum and your upper bounds. Also, in your example, you cut off the y axis, where you there is actually shaded area below.

Y1 = np.maximum(y0, y3)
Y2 = np.minimum(y1, y2)
plt.fill_between(x, Y1, Y2, where = Y1 < Y2, color = 'grey', alpha = 0.5)

这篇关于使用 fill_between 和 min/max 来表示不等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆