Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a trend line to this data frame (Python)

I was wondering how I could add a trend line (or line of best fit) to my bar graph. I have tried searching but have only found myself confused. Here is the code that I use to create the bar graph:

    dfY = pd.DataFrame(data={"Year":dataYVote['Year'], "Vote": dataYVote['Vote']})
    year_list = []
    avg_votes = []
    for year in np.unique(dfY["Year"]):
        year_list.append(year)
        avg_votes.append(dfY.loc[dfY["Year"]==year, "Vote"].mean())
    
    plt.bar(year_list, avg_votes, width = 0.5)
    plt.xlabel('Year')
    plt.ylabel('Amount of Votes')
    plt.title('Average Amount of Votes for Each Year')
    plt.show() 

Any help is much appreciated :)

like image 699
BioFluorescent277 Avatar asked Apr 21 '26 15:04

BioFluorescent277


1 Answers

You could use a numpy.polyfit which minimizes the squared error and returns the gradient and intercept.

import numpy as np

slope, intercept = np.polyfit(x_data, y_data, 1) #deg of 1 for straight line
plt.plot(x, slope*x + intercept)
like image 144
GhandiFloss Avatar answered Apr 23 '26 04:04

GhandiFloss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!