简体   繁体   中英

Line of Best fit on Matplotlib

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()

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM