延伸线超过2个控制点

21
在matplotlib中,我们可以使用至少2种方法绘制线条:
  • plt.plot

    plt.plot([1,2],[1,2],color='k',marker='o')
    
  • Line2D method

    line = lines.Line2D([0.3,0.6],[0.9,0.3],linestyle='dashed',color='k')
    plt.axes().add_line(line)
    
  • 我怀疑这两种方法在实现上是相同的。但无论如何,它确实在两个指定点之间画出一条直线。有时我需要将线段延伸到图表的极限之上。当然我可以用y=ax+b的形式来计算,但有没有更简单的方法呢?
    如果我能找到一些额外的选项就太完美了,但我找不到。

    我认为没有直接的方法。请注意,线是从n个元素的数组中绘制的。也就是说,它们被设计成不是直的。要以通用形式扩展Line2D,您需要查看线头和尾处的最后两对点。这很奇怪,可能没有考虑到仅由两个点组成的特殊情况,因为在这种情况下确实有意义。 - joaquin
    +1 表示 plt.plot([1,2],[1,2],color='k',marker='o') - Sibbs Gambling
    4个回答

    7

    午饭后,我能够找到一种使用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')
    

    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

    我有点晚了,但是我在谷歌上搜索的时候发现了这个。我也厌倦了在matplotlib中无法做到这一点,所以我写了abline_plot。它包括回调函数,以便在轴限制更改时更新2D线。

    在下面的链接中搜索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()
    

    2

    虽然回答晚了,但我会为像我一样偶然发现这个问题的人提供最简单的答案:

    从 matplotlib 3.3 开始,您可以使用 plt.axline((x1, y1), (x2, y2)) 来实现此功能。


    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接