python - 如何填充matplotlib中线之间的区域

标签 python matplotlib pulp

我想在 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 轴,并切换 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'$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

关于python - 如何填充matplotlib中线之间的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55740846/

相关文章:

python - 如何在没有任何控件可见的情况下显示 matplotlib 交互式窗口?

matplotlib - 如何使用 pandas.DataFrame.boxplot 的返回值?

python - 我如何限制 COIN-CBC 的运行时间,因为 maxSeconds 参数似乎对我不起作用?

python - 如何配置 PuLP 调用 GLPK 求解器

python - 如何以最快的速度向我的用户发布 100,000 条独特的消息?

python - 打印用于复制和粘贴的 numpy 数组

python - 绘图 : vertical gradient fill under curve?

python - PuLP :在循环中添加多个 LpSum

python - 如何获得世界空间中二维点的射线方程

python - 如何在没有装饰器的情况下使用 lru_cache?适用于 3.8,不适用于 3.6