Python Matplotlib:绘制线性不等式函数

10

3
你尝试过什么?是否查看了画廊?我认为fill_between函数可以实现你想要的效果。这是链接http://matplotlib.org/examples/pylab_examples/fill_between_demo.html - tacaswell
1个回答

22

我写了一个非常简单的例子,仅适用于你的问题,但很容易扩展和推广。唯一的技巧是使用SymPy来简化找到根以建立所需多边形的问题。(摘自 http://docs.sympy.org/dev/modules/solvers/solvers.html)

import numpy as np
import matplotlib.pyplot as plt
from sympy.solvers import solve
from sympy import Symbol

def f1(x):
    return 4.0*x-2.0
def f2(x):
    return 0.5*x+2.0
def f3(x):
    return -0.3*x+7.0

x = Symbol('x')
x1, =  solve(f1(x)-f2(x))
x2, =  solve(f1(x)-f3(x))
x3, =  solve(f2(x)-f3(x))

y1 = f1(x1)
y2 = f1(x2)
y3 = f2(x3)

plt.plot(x1,f1(x1),'go',markersize=10)
plt.plot(x2,f1(x2),'go',markersize=10)
plt.plot(x3,f2(x3),'go',markersize=10)

plt.fill([x1,x2,x3,x1],[y1,y2,y3,y1],'red',alpha=0.5)

xr = np.linspace(0.5,7.5,100)
y1r = f1(xr)
y2r = f2(xr)
y3r = f3(xr)

plt.plot(xr,y1r,'k--')
plt.plot(xr,y2r,'k--')
plt.plot(xr,y3r,'k--')

plt.xlim(0.5,7)
plt.ylim(2,8)

plt.show()

这里输入图像描述

敬礼


你如何处理大于或小于等于符号?换句话说,你会如何编写 y <= 7 -0.3x 和 y >= 7 -0.3x? - Vivek
这个解决方案现在导致:ImportError: SymPy 现在依赖于 mpmath 作为外部库。请参阅 https://docs.sympy.org/latest/install.html#mpmath 获取更多信息。 - seeker_after_truth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接