Home > database >  How to plot a Parabola and the points using plt?
How to plot a Parabola and the points using plt?

Time:11-16

I have the following list of points:

[[1,10],[2,5.49],[3,0.89],[4,-0.14],[5,-1.07],[6,0.84]]

I calculated the parabola which goes through those points y=0.83535714x^2-7.74778571x 17.116. The values:

> print(matrix)
 [[ 0.83535714]
 [-7.74778571]
 [17.116     ]]

Also, I have splited the points:

points = np.asarray([[1,10],[2,5.49],[3,0.89],[4,-0.14],[5,-1.07],[6,0.84]])
points_x_axis = points[:, 0]
points_y_axis = points[:, 1]

Now I want to plot the Parabola and the points. How can I do it?

CodePudding user response:

Using Polynomial regression to smooth the graph

import numpy as np    
import matplotlib.pyplot as plt

def parabola(x):
    return 0.83535714*x**2-7.74778571*x 17.116

x = np.linspace(0, 9, 100)
y = parabola(x)

plt.plot(x, y)
plt.scatter(points_x_axis, points_y_axis)
plt.show()

enter image description here


#Simple plotting    
import matplotlib.pyplot as plt
plt.plot(points_x_axis, points_y_axis, 'o')
plt.plot(points_x_axis, 0.83535714*points_x_axis**2-7.74778571*points_x_axis 17.116)
plt.show()

Output:

enter image description here

CodePudding user response:

Use np.polyfit and np.polyval:

data = np.array([[1,10],[2,5.49],[3,0.89],[4,-0.14],[5,-1.07],[6,0.84]])
p = np.polyfit(data[:, 0], data[:, 1], 2)
x = np.linspace(0, 9, 100)
y = np.polyval(p, x)
plt.plot(x, y)
plt.plot(data[:, 0], data[:, 1], 'k.')
  • Related