from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(30,79,20)
y = np.linspace(40,100,20) + np.random.randint(10,size=20)
plt.figure(figsize=(6,6))
cmax = max(max(x),max(y))
cmin = min(min(x),min(y))
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
X1 = np.arange (0,int(cmax),100)
Y1 = np.array([ intercept+ slope * x for x in X1])
plt.plot(X1,Y1)
plt.xlim(cmin,cmax )
plt.ylim(cmin,cmax )
X2 = np.linspace(0,cmax*1.1,5)
Y2 = np.linspace(0,cmax*1.1,5)
plt.xticks(X2)
plt.yticks(Y2)
plt.plot(range(int(cmax*1.1)),color='black')
plt.scatter(x,y)
plt.text(cmax*0.1,cmax*0.9,'R$^2$=%s'%(np.around(r_value**2,2)),fontsize=20)
plt.text(cmax*0.1,cmax*0.8,'y=%s*x+%s'%(np.around(slope,2),np.around(intercept,2)),fontsize=15)
plt.xlabel('坐标轴x',fontproperties='KaiTi',fontsize=20)
plt.ylabel('坐标轴y',fontproperties='KaiTi',fontsize=20)
plt.tick_params(labelsize=15)
plt.savefig('test.jpg',bbox_inches='tight',dpi=300)
- 散点图无截距线性拟合+中文楷体英文Times New Roman (2023/04/27)
from scipy import optimize
from sklearn.metrics import r2_score
def fun1(x, a):
return a * x
slope = optimize.curve_fit(fun1,x,y)[0][0]
r = r2_score(slope*x,y)
config = {
"font.family":'serif',
"font.size": 20,
"mathtext.fontset":'stix',
"font.serif": ['Times New Roman'],
}
plt.rcParams.update(config)
X1 = np.arange (0,int(cmax),100)
Y1 = np.array([ slope * x for x in X1])
plt.plot(X1,Y1)
plt.xlim(cmin,cmax )
plt.ylim(cmin,cmax )
X2 = np.linspace(0,cmax*1.1,5)
Y2 = np.linspace(0,cmax*1.1,5)
plt.xticks(X2)
plt.yticks(Y2)
plt.plot(range(int(cmax*1.1)),color='black')
plt.scatter(x,y)
plt.text(cmax*0.1,cmax*0.9,'R$^2$=%s'%(np.around(r**2,2)),fontsize=20)
plt.text(cmax*0.1,cmax*0.8,'y=%s*x'%(np.around(slope,2)),fontsize=15)
plt.xlabel('坐标轴$\mathrm{Xlabel}$',fontproperties='KaiTi',fontsize=20)
plt.ylabel('坐标轴$\mathrm{Ylabel}$',fontproperties='KaiTi',fontsize=20)
plt.tick_params(labelsize=15)
plt.show()
字体设置