簡體   English   中英

如何 plot 一條帶斜率和一個點的線? Python

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

我試圖通過一個點畫一條線,只給定點和線的斜率。 更具體地說,我的斜率為 -2 且只有 (3,4) 的一個點,我試圖通過它畫一條線。 任何幫助,將不勝感激。

您有足夠的信息來計算經典直線公式的 y 截距。 從那里開始,只需計算線的幾個點並將它們繪制出來:

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()

這可以通過matplotlib>=3.3.4中的axline輕松完成:

pip install --upgrade matplotlib>=3.3.4

例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM