matplotlib:在两个控制点上扩展行?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (15)

在matplotlib中,我们可以使用至少2种方法绘制直线:

  1. plt.plot plt.plot([1,2],[1,2],color='k',marker='o')
  2. Line2D method line = lines.Line2D([0.3,0.6],[0.9,0.3],linestyle='dashed',color='k') plt.axes().add_line(line)

当然,我怀疑这两种方法是相同的。但是无论如何,它在两个声明的点之间划了一条线。有更好的方法吗?

提问于
用户回答回答于

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()
用户回答回答于

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

扫码关注云+社区