问题
I have some snippets of code that read two csvs and plot them using matplotlib.pyplot and perform polynomial regression on the same two csvs. What I want to be able to do is plot both the data and my polynomial regression on the same graph.
import matplotlib.pyplot as plt
import csv
import numpy as np
datax=np.genfromtxt('Delta R.csv')
datay=np.genfromtxt('Example R.csv')
plt.title ('Test graph ')
plt.xlabel('x axis')
plt.ylabel('y axis ')
plt.plot(datax, datay,'o-')
plt.show()
and my second piece of code performs simply polynomial regression
import matplotlib.pyplot as plt
import csv
import numpy as np
datax=np.genfromtxt('Delta R.csv')
datay=np.genfromtxt('Example R.csv')
z = np.polyfit(datax,datay,5)
print z
Can anybody help me plot the results of this 5th order polynomail regression in the same plot as the original data. Thanks GTPE
edit
Code provided by tcaswell works perfectly. My only question is why does the polynomial come out so angular in places. Here is my example image:
回答1:
Just call plot
again:
datax=np.genfromtxt('Delta R.csv')
datay=np.genfromtxt('Example R.csv')
z = np.polyfit(datax,datay,5)
p = np.poly1d(z)
plt.title ('Test graph ')
plt.xlabel('x axis')
plt.ylabel('y axis ')
plt.plot(datax, datay,'o-')
plt.plot(datax, p(datax), '-')
datax_os = np.linspace(np.min(datax), np.max(datax), 1024)
plt.plot(datax_os, f(datax_os)) # 'smoother' line
plt.show()
An alternate method using multiple arguements to plot
can be seen in the np.polyfit
documentation.
来源:https://stackoverflow.com/questions/19191382/plotting-polynomial-regression-in-same-plot-as-the-real-data