Search code examples
pythonmatplotlibmathgraphing

Graph parabola in matplotlib with vertex and 2 'end' points known


Trying to create a parabolic vector of values where the Vertex and two other points along the parabola are known.

Example...

  • Range from 0 to 10
  • Vertex = [5,2]
  • Coordinate 1 = [1,1]
  • Coordinate 2= [10,1]

Example Desired result

Any help/advice is greatly appreciated.

Thanks


Solution

  • I would use numpy to adjust a parabola passing by the points with polyfit, and then polyval to evaluate the polynomial found:

    import matplotlib.pyplot as plt
    import numpy as np
    
    #points
    x = [1, 5, 10]
    y = [1, 2, 1]
    
    poly_coeffs = np.polyfit(x,y,2) #fit a polynomial with degree=2
    
    #evaluation points vector xx
    xmin = 0
    xmax = 10
    xx = np.linspace(xmin, xmax, 100)
    yy = np.polyval(poly_coeffs, xx) #y coords
    
    #ploting
    plt.figure()
    plt.plot(x,y,'or')
    plt.plot(xx,yy)
    plt.grid()
    plt.ylim([-3,4])
    plt.xlim([-0.5,12])
    

    This would draw the next image: