問題描述
如何繪製一條帶斜率和一個點的線?Python (How to plot a line with slope and one point given? Python)
我試圖通過一個點畫一條線,只給定點和線的斜率。更具體地說,我的斜率為 ‑2 且只有 (3,4) 的一個點,我試圖通過它畫一條線。任何幫助將不勝感激。
參考解法
方法 1:
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()
方法 2:
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')
(by may7even、Anon Coward、RJ Adriaansen)