如何在 matplotlib 中填充线条之间的区域

how to fill area between lines in matplotlib

我想在 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'A+4B\leq30$')
plt.plot(A, y2, label=r'A+6B\leq60$')
plt.plot(A, y3, label=r'.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

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

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

如果您指的是另一条曲线,则类似地用 y2 替换 y3。 "Maximized area" 有点误导,正如@gmds 已经评论过的那样。

这是一种基于thislink的解决方案。与 linked 解决方案的唯一区别是,对于您的情况,我不得不使用 fill_betweenx 覆盖曲线共有的整个 x 轴,并切换 xY。这个想法是首先在一定公差范围内找到交点,然后从位于该点左侧的一条曲线和位于该交点右侧的另一条曲线中获取值。我还必须在 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'A+4B\leq30$')
plt.plot(A, y2, label=r'A+6B\leq60$')
plt.plot(A, y3, label=r'.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)