如何填充matplotlib中的行之间的区域

问题描述 投票:1回答:2

我想在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()

想要填充格言区域x = 2.0和y = 6.0

python matplotlib pulp
2个回答
2
投票

这是一个基于this链接的解决方案。与链接解决方案的唯一区别在于,对于您的情况,我必须使用fill_betweenx来覆盖曲线的整个x轴并切换xY的顺序。我们的想法是首先在一定的公差范围内找到交点,然后从左边的一条曲线到该点,另一条曲线位于交叉点的右边。我还必须在[0]中添加额外的ind以使其正常工作

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)

enter image description here


0
投票

我假设你想要填充y1y3之间的区域,直到它们相互交叉,因为你指定(2,6)作为一个点?然后使用:

plt.fill_between(A, y1, y3, where = y1<y3)

如果你的意思是另一条曲线,则类似地将y3替换为y2。 @gmds已经评论过,“最大化区域”有点误导。

© www.soinside.com 2019 - 2024. All rights reserved.