I need to plot two straight lines on a single graph. The equations are of the form ax +by + c=0, where:
x = x-coordinate y = y-coordinate a, b, c are coefficients
Thanks!
I need to plot two straight lines on a single graph. The equations are of the form ax +by + c=0, where:
x = x-coordinate y = y-coordinate a, b, c are coefficients
Thanks!
Something like this worked for me, using matplotlib's axline function, and a function to handle the conversion of the a,b,c parameters to an arbitrary pair of points:
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()