Search code examples
pythondataframematplotlibtrendline

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


Solution

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