【问题标题】:How do I add a trend line to this data frame (Python)如何向此数据框添加趋势线(Python)
【发布时间】:2020-09-08 08:25:12
【问题描述】:

我想知道如何在我的条形图中添加一条趋势线(或最佳拟合线)。我试过搜索,但发现自己很困惑。这是我用来创建条形图的代码:

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

非常感谢任何帮助:)

【问题讨论】:

    标签: python dataframe matplotlib trendline


    【解决方案1】:

    您可以使用numpy.polyfit 来最小化平方误差并返回梯度和截距。

    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)
    

    【讨论】:

    • 谢谢,这行得通。只是一个问题,最后一行中的 x 代表什么。我需要用一个值替换它吗?
    • 那是你的x数据,y数据由y=mx + c计算。为您提供最合适的产品线
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2021-07-05
    • 2019-06-15
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    相关资源
    最近更新 更多