Reputation:
I'm trying to plot a line of best fit on my auto generated graph. My graph is currently just a plain scatter graph. I've looked at various solutions to this, however, they all provide a solution to a different method of plotting the graph.
My code loops through lists in order to plot the data stored in them.
I'm wondering if there is a way of implementing a line of best fit with this method or whether I'll have to change it; if an explanation could be given as to how to change it to work, that would be appreciated.
for x in range (0,len(profits)):
plt.plot([yearofreleaselist[x]], [profits[x]], '-ro')
plt.annotate((filmlist[x]), xy=(yearofreleaselist[x], profits[x]))
oldestfilm = len(yearofreleaselist)
oldestfilm = oldestfilm-1
plt.axis([(int(yearofreleaselist[oldestfilm])-1), (int(yearofreleaselist[0]))+1, 0, (max(profits))+50000000])
plt.ylabel("Profit ($)")
plt.xlabel("Year Of Release")
name = str(textbox1.get())
plt.title("The Profits of " + name.title() + "'s films")
plt.savefig(name+'.png')
text3["text"] = plt.show()
Upvotes: 0
Views: 5726
Reputation: 1075
If you want a linear best fit, how about:
import numpy as np
import matplotlib.pyplot as plt
plt.plot(yearofreleaselist, np.poly1d(np.polyfit(yearofreleaselist, profits, 1))(yearofreleaselist))
Upvotes: 1