plotting polynomial regression in same plot as the real data

梦想的初衷 提交于 2021-02-19 04:24:15

问题


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:

enter image description here


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!