在matplotlib中,我们可以使用至少两种方法绘制线条:
plt.plot
plt.plot([1,2],[1,2],color='k',marker='o')
Line2D方法
line = lines.Line2D([0.3,0.6],[0.9,0.3],linestyle='dashed',color='k')
plt.axes().add_line(line)
我怀疑这两种方法在实施过程中都是一样的。但无论如何,它在两个陈述点之间准确划出一条线。有时我需要将这两个点扩展到图形限制。当然我可以用y = ax + b的形式来计算它,但有人知道更容易吗?
如果我可以添加一些额外的选项,但是我无法找到它。
答案 0 :(得分:6)
午餐过后,我找到了一种使用numpy的方式。
def drawLine2P(x,y,xlims):
xrange = np.arange(xlims[0],xlims[1],0.1)
A = np.vstack([x, np.ones(len(x))]).T
k, b = np.linalg.lstsq(A, y)[0]
plt.plot(xrange, k*xrange + b, 'k')
答案 1 :(得分:3)
这个晚了一点,但我只是在谷歌搜索时遇到过这个。我也厌倦了无法在matplotlib中做到这一点,所以我写了abline_plot。它包括在轴限制发生变化时更新2D线的回调。
在下面的链接中搜索abline_plot示例。
http://statsmodels.sourceforge.net/devel/examples/generated/example_interactions.html
文档:
实现:
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/graphics/regressionplots.py#L572
编辑:一个不更新的简单
import matplotlib.pyplot as plt
from matplotlib import lines as mpl_lines
def slope_from_points(point1, point2):
return (point2[1] - point1[1])/(point2[0] - point1[0])
def plot_secant(point1, point2, ax):
# plot the secant
slope = slope_from_points(point1, point2)
intercept = point1[1] - slope*point1[0]
# update the points to be on the axes limits
x = ax.get_xlim()
y = ax.get_ylim()
data_y = [x[0]*slope+intercept, x[1]*slope+intercept]
line = mpl_lines.Line2D(x, data_y, color='red')
ax.add_line(line)
return ax.figure()
答案 2 :(得分:3)
希望这有帮助
import matplotlib.pyplot as plt
# I am generating 2 random points, u might want to update these
x1,y1,x2,y2 = np.random.uniform(-1,1,4)
# make use of line equation to form function line_eqn(x) that generated y
line_eqn = lambda x : ((y2-y1)/(x2-x1)) * (x - x1) + y1
# generate range of x values based on your graph
xrange = np.arange(-1.2,1.2,0.2)
# plot the line with generate x ranges and created y ranges
plt.plot(xrange, [ line_eqn(x) for x in xrange], color='k', linestyle='-', linewidth=2)
答案 3 :(得分:0)
太晚了,但对于像我一样偶然发现这个问题的人来说,这是最简单的答案,
从 matplotlib 3.3 开始,您可以使用 plt.axline((x1, y1), (x2, y2))
执行此操作。