繁体   English   中英

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

[英]Iterate through linear regression while outputting plots In Python (SciPy & MatPlotLib)

尝试遍历一个 for 循环,该循环在 pandas dataframe 上运行 3 个回归,同时为每个变量打印行的 plot。

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”和不同回归线的图,但我想知道如何为每个 plot 相对于循环中的每个变量设置相对标题(和标签)。 不确定如何从我引用的列表中检索变量名称。 在字幕行中尝试了str(x) ,但返回的是列中的值而不是列表标题。

像这样的东西?

import numpy as np
import matplotlib.pyplot as plt

matrix = np.random.rand(4,12)  # emulate some data
crime_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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM