【问题标题】:Fill in feasible region with Fill_between用 Fill_between 填充可行域
【发布时间】:2023-03-03 00:47:01
【问题描述】:

我正在尝试填写图片中附加的最大向外区域。下面的代码将生成折线图,但是,我正在努力填充图像中的区域。

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(0,20,2000)
y1 = (-2*x) + 6
y2 = 5-x
y3 = (20 - (2*x))/10
plt.plot(x,y1,label = r'$2x1+x2geq6$')
plt.plot(x,y2,label = r'$x+ygeq5$')
plt.plot(x,y3,label = r'$2x+10ygeq20$')
plt.xlim((0,10))
plt.ylim((0,10))
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')

【问题讨论】:

  • 你试过你在标题中提到的fill_between方法吗?

标签: python numpy matplotlib plot linear-programming


【解决方案1】:

最简单的方法是使用 3 条曲线中的最大值:


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 2000)
y1 = (-2 * x) + 6
y2 = 5 - x
y3 = (20 - (2 * x)) / 10
plt.plot(x, y1, label=r'$2x1+x2geq6$')
plt.plot(x, y2, label=r'$x+ygeq5$')
plt.plot(x, y3, label=r'$2x+10ygeq20$')
plt.fill_between(x, np.amax([y1, y2, y3], axis=0), 10, color='black', alpha=0.3)
plt.xlim((0, 10))
plt.ylim((0, 10))
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.show()

【讨论】:

  • 如果这回答了您的问题,您可能会将marking 的答案视为已接受
【解决方案2】:

您可以用一种颜色填充整个背景,然后使用fill_between 将线条下方的区域设置为白色。

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

plt.rcParams['axes.facecolor'] = 'lightgrey'

x = np.linspace(0,20,2000)
y1 = (-2*x) + 6
y2 = 5-x
y3 = (20 - (2*x))/10
plt.plot(x,y1,label = r'$2x1+x2geq6$')
plt.plot(x,y2,label = r'$x+ygeq5$')
plt.plot(x,y3,label = r'$2x+10ygeq20$')
plt.xlim((0,10))
plt.ylim((0,10))
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')

plt.fill_between(x,y3, color='white')
plt.fill_between(x,y2, color='white')
plt.fill_between(x,y1, color='white');

【讨论】:

  • 嗨,克里斯,非常感谢!
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
相关资源
最近更新 更多