首页 > 技术文章 > plt常用

skypanxh 2022-03-27 13:52 原文

1.绘制散点图、拟合方程、R方

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import stats
    
df = pd.read_excel("all_mean.xlsx")
columns = list(df.columns)
for i in range(2,len(columns)):
    x_list = list(df[columns[1]])
    y_list = list(df[columns[i]])
    
    slope, intercept, r_value, p_value, std_err = stats.linregress(np.array(x_list), np.array(y_list))
    
    _X1 = [0, 7]
    _Y1 = [intercept + slope * x for x in _X1]
    
    plt.xlim(xmax=6,xmin=0)
    plt.ylim(ymax=round(max(y_list)),ymin=0)
    plt.xlabel(columns[1])
    plt.ylabel(columns[i])
    plt.plot(x_list,y_list,'ro')
    
    plt.plot(_X1, _Y1, 'b',linewidth=2)
    plt.text(0.5,0.6,"y = {} + {}x".format(str(intercept),str(slope)))
    plt.title("R2 = {}".format(str(r_value**2)))
    plt.savefig("plots/{}.png".format(columns[i]))
    plt.show()

推荐阅读