如何向此数据框添加趋势线 (Python)
How do I add a trend line to this data frame (Python)
我想知道如何将趋势线(或最佳拟合线)添加到我的条形图中。我试过搜索,但只发现自己很困惑。这是我用来创建条形图的代码:
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()
非常感谢任何帮助:)
您可以使用 numpy.polyfit
来最小化平方误差和 returns 梯度和截距。
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)
我想知道如何将趋势线(或最佳拟合线)添加到我的条形图中。我试过搜索,但只发现自己很困惑。这是我用来创建条形图的代码:
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()
非常感谢任何帮助:)
您可以使用 numpy.polyfit
来最小化平方误差和 returns 梯度和截距。
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)