首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >matplotlib:超过2个控制点的延长线

matplotlib:超过2个控制点的延长线
EN

Stack Overflow用户
提问于 2012-02-05 19:40:02
回答 4查看 12.1K关注 0票数 20

在matplotlib中,我们可以使用至少两种方法来绘制线条:

  1. plt.plot

颜色(1,2,1,2,plt.plot=‘k’,marker='o')

  • Line2D方法

plt.axes().add_line(line) = lines.Line2D(0.3,0.6,0.9,0.3,line =‘虚线’,color='k')行

当然,我怀疑这两种方法在实现上是相同的。但不管怎样,它在两个指定的点之间画了一条线。有时我需要将这两个点上的线延伸到图形极限。我当然可以用y=ax+b的形式来计算它,但是有谁知道更简单的方法吗?

如果我可以添加一些额外的选项,那就完美了,但我找不到它。

EN

回答 4

Stack Overflow用户

发布于 2012-02-06 05:55:21

在吃了一顿丰盛的午餐后,我找到了一种使用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')
票数 7
EN

Stack Overflow用户

发布于 2013-01-27 05:59:04

这方面有点晚了,但我是在谷歌搜索的时候发现的。我也厌倦了不能在matplotlib中做到这一点,所以我写了abline_plot。它包括在轴限制更改时更新二维线的回调。

在下面的链接中搜索abline_plot示例。

http://statsmodels.sourceforge.net/devel/examples/generated/example_interactions.html

文档:

http://statsmodels.sourceforge.net/devel/generated/statsmodels.graphics.regressionplots.abline_plot.html#statsmodels.graphics.regressionplots.abline_plot

实施:

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()
票数 3
EN

Stack Overflow用户

发布于 2016-10-31 11:28:04

希望这能有所帮助

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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9148927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档