在 Python 中输出绘图时迭代线性回归(SciPy 和 MatPlotLib)

尝试遍历一个 for 循环,该循环在 pandas 数据帧上运行 3 个回归,同时为每个变量打印一条线图。


year = crime_df.iloc[:,0]

violent_crime_rate = crime_df.iloc[:,3]

murder_rate = crime_df.iloc[:,5]

aggravated_assault_rate = crime_df.iloc[:,11]



x_axis = [violentcrimerate, murderrate, aggravatedassaultrate]



for x in x_axis:

    slope, intercept, r_value, p_value, std_err = linregress(year, x)

    fit = slope * year + intercept



    fig, ax = plt.subplots()


    fig.suptitle('x', fontsize=16, fontweight="bold")


    ax.plot(year, x, linewidth=0, marker='o')

    ax.plot(year, fit, 'b--')



    plt.show()

代码生成 3 个标题为“x”的图和不同的回归线,但我想知道如何为每个图设置相对于循环中每个变量的相对标题(和标签)。不确定如何从我引用的列表中检索变量名称。在字幕行中尝试过str(x),但返回的是列中的值而不是列表标题。


湖上湖
浏览 153回答 1
1回答

凤凰求蛊

像这样的东西?import numpy as npimport matplotlib.pyplot as pltmatrix = np.random.rand(4,12)  # emulate some datacrime_df = pd.DataFrame(matrix)# emulate some data year = crime_df.iloc[:,0]violent_crime_rate = crime_df.iloc[:,3]murder_rate = crime_df.iloc[:,5]aggravated_assault_rate = crime_df.iloc[:,11]names = ['violent_crime_rate','murder_rate','aggravated_assault_rate']x_axis = [violent_crime_rate, murder_rate, aggravated_assault_rate]def linregress(year,x):  #emulate some data    return np.random.rand(5)for ind, x in enumerate(x_axis):    slope, intercept, r_value, p_value, std_err = linregress(year, x)    fit = slope * year + intercept    fig, ax = plt.subplots()    fig.suptitle('x:'+str(names[ind]), fontsize=16, fontweight="bold")    ax.plot(year, x, linewidth=0, marker='o', label = names[ind] + ':1')    ax.plot(year, fit, 'b--', label = names[ind] + ':2')    ax.legend()    plt.show()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python