繁体   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