两个控制点之间延长线

21 投票
4 回答
14133 浏览
提问于 2025-04-17 12:22

在matplotlib中,我们可以用至少两种方法来画线:

  1. plt.plot

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

    line = lines.Line2D([0.3,0.6],[0.9,0.3],linestyle='dashed',color='k')
    plt.axes().add_line(line)
    

我觉得这两种方法的实现应该差不多。不过无论如何,它们都是在两个指定的点之间画一条线。有时候我想把这条线延伸到图表的边界。虽然我可以用y=ax+b的方式来计算,但有没有更简单的方法呢?

如果能只加个选项就能实现那就太好了,但我找不到这样的选项。

4 个回答

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

撰写回答