我想在 matplotlib 中绘图后从下面的方程中填充最大化区域 尝试了所有可能性,但无法填充所需的区域。
import numpy as np
import matplotlib.pyplot as plt
A = np.linspace(0, 100, 2000)
# 3A+4B≤30
y1 = (30 - A * 3 ) /4
# 5A+6B≤60
y2 = (60 - A * 5)/6
# 1.5A+3B≤21
y3 = (21 - A * 1.5)/3.0
plt.plot(A, y1, label=r'$3A+4B\leq30$')
plt.plot(A, y2, label=r'$5A+6B\leq60$')
plt.plot(A, y3, label=r'$1.5A+3B\leq21$')
plt.xlim((0, 20))
plt.ylim((0, 15))
plt.xlabel(r'$x values$')
plt.ylabel(r'$y values$')
plt.fill_between(A, y3, where = y2<y3,color='grey', alpha=0.5)
plt.legend(bbox_to_anchor=(.80, 1), loc=2, borderaxespad=0.1)
plt.show()
想要填充 maxim 的区域,即 x = 2.0 和 y = 6.0
最佳答案
这是一个基于 this 的解决方案关联。与链接解决方案的唯一区别是,对于您的情况,我必须使用 fill_ Betweenx
覆盖曲线共有的整个 x 轴,并切换 x
和Y
。这个想法是首先找到一定公差范围内的交点,然后从位于该点左侧的一条曲线和位于交点右侧的另一条曲线中获取值。我还必须在 ind
中添加一个额外的 [0]
才能使其正常工作
import numpy as np
import matplotlib.pyplot as plt
A = np.linspace(0, 100, 2000)
y1 = (30 - A * 3 ) /4
y2 = (60 - A * 5)/6
y3 = (21 - A * 1.5)/3.0
plt.plot(A, y1, label=r'$3A+4B\leq30$')
plt.plot(A, y2, label=r'$5A+6B\leq60$')
plt.plot(A, y3, label=r'$1.5A+3B\leq21$')
plt.xlim((0, 20))
plt.ylim((0, 12))
plt.xlabel(r'$x values$')
plt.ylabel(r'$y values$')
plt.legend(bbox_to_anchor=(.65, 0.95), loc=2, borderaxespad=0.1)
def fill_below_intersection(x, S, Z):
"""
fill the region below the intersection of S and Z
"""
#find the intersection point
ind = np.nonzero( np.absolute(S-Z)==min(np.absolute(S-Z)))[0][0]
# compute a new curve which we will fill below
Y = np.zeros(S.shape)
Y[:ind] = S[:ind] # Y is S up to the intersection
Y[ind:] = Z[ind:] # and Z beyond it
plt.fill_betweenx(Y, x, facecolor='gray', alpha=0.5) # <--- Important line
fill_below_intersection(A, y3, y1)
关于python - 如何填充matplotlib中线之间的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55740846/