may7even
may7even

Reputation: 129

How to plot a line with slope and one point given? Python

I'm trying to draw a line through a point with only the point and the slope of the line given. More specifically, I have a slope of -2 and only one point of (3,4), and I'm trying to draw a line through it. Any help would be appreciated.

Upvotes: 1

Views: 4252

Answers (2)

RJ Adriaansen
RJ Adriaansen

Reputation: 9619

This can be easily done with axline in matplotlib>=3.3.4:

pip install --upgrade matplotlib>=3.3.4

Example:

import matplotlib.pyplot as plt
plt.axline((3, 4), slope=-2, linewidth=4, color='r')

Upvotes: 4

Anon Coward
Anon Coward

Reputation: 10826

You have enough information to calculate the y intercept for the classic line formula. From there, it's just a matter of calculating a couple of points of the line and plotting them out:

import matplotlib.pyplot as plt
pt = (3, 4)
slope = -2

# Given the above, calculate y intercept "b" in y=mx+b
b = pt[1] - slope * pt[0]

# Now draw two points around the input point
pt1 = (pt[0] - 5, slope * (pt[0] - 5) + b)
pt2 = (pt[0] + 5, slope * (pt[0] + 5) + b)

# Draw two line segments around the input point
plt.plot((pt1[0], pt[0]), (pt1[1], pt[1]), marker = 'o')
plt.plot((pt[0], pt2[0]), (pt[1], pt2[1]), marker = 'o')

plt.show()

Upvotes: 2

Related Questions