-2

我需要在一个图表上绘制两条直线。方程的形式为 ax +by + c=0,其中:

x = x 坐标 y = y 坐标 a, b, c 是系数

谢谢!

4

1 回答 1

0

像这样的东西对我有用,使用 matplotlib 的axline 函数和一个函数来处理 a,b,c 参数到任意点对的转换:

import matplotlib.pyplot as plt

def linePoints(a=0,b=0,c=0,ref = [-1.,1.]):
    """given a,b,c for straight line as ax+by+c=0, 
    return a pair of points based on ref values
    e.g linePoints(-1,1,2) == [(-1.0, -3.0), (1.0, -1.0)]
    """
    if (a==0 and b==0):
        raise Exception("linePoints: a and b cannot both be zero")
    return [(-c/a,p) if b==0 else (p,(-c-a*p)/b) for p in ref]

# test linePoints function: 
assert linePoints(-1,1,2) == [(-1.0, -3.0), (1.0, -1.0)], "linePoints error"

# draw a test chart with matplotlib:
fig,ax = plt.subplots()
ax.axline(*linePoints(a=0,b=1,c=0),color="red",label="horizontal")   
ax.axline(*linePoints(a=1),color="blue",label="vertical")
ax.axline(*linePoints(0,1,-1),color="yellow",label="horizontal offset")   
ax.axline(*linePoints(1,0,-1,[-2.,0.]),color="green",label="vertical offset")
ax.axline(*linePoints(1,-2,0.5),color="purple",label="shallow diagonal")
ax.axline(*linePoints(2,-1,-0.5,[-2,2]),color="violet",label="steep diagonal")
ax.axline(*linePoints(1,1,-1),color="orange",label="reverse diagonal")
#plt.axline(*linePoints(c=1),color="grey",label="will fail: a or b must be set")
ax.set_aspect('equal')
plt.xlim([-6,6])
plt.legend()
#plt.savefig('linePoints.png')
plt.show()

线图输出

于 2021-02-24T12:45:39.093 回答