微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:有没有办法绘制 ax + by + c = 0 形式的线的标准方程

如何解决Python:有没有办法绘制 ax + by + c = 0 形式的线的标准方程

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

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

谢谢!

解决方法

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

import matplotlib.pyplot as plt

def linePoints(a=0,b=0,c=0,ref = [-1.,1.]):
    """given a,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.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),color="yellow",label="horizontal offset")   
ax.axline(*linePoints(1,-1,[-2.,0.]),color="green",label="vertical offset")
ax.axline(*linePoints(1,-2,0.5),color="purple",label="shallow diagonal")
ax.axline(*linePoints(2,-0.5,[-2,2]),color="violet",label="steep diagonal")
ax.axline(*linePoints(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()

Line plot output

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。