def temp(filename,x,dic): path='excelFile/'+filename df = pandas.read_excel(path,header=None) data = [] datax = df.iloc[0].tolist() datay=df.iloc[1].tolist() transInt(datax) transInt(datay) slope,intercept,r,p,std_err=stats.linregress(datax,datay) def myfunc(datax): return slope*datax+intercept mymodel=list(map(myfunc,datax)) plt.scatter(datax,datay) plt.plot(datax,mymodel) print(x) result=myfunc(int(x)) if r>=0.7 or r<=-0.7: count=2 while count<6 : mymodel_2=numpy.poly1d(numpy.polyfit(datax,datay,count)) myline=numpy.linspace(min(datax),max(datay),100) r2=r2_score(datay,mymodel_2(datax)) plt.scatter(datax,datay) plt.plot(myline,mymodel_2(myline)) result=mymodel_2(int(x)) if r2>=0.7 or r2<=-0.7: break plt.savefig('figs/result.png') dic['Y']=str(result)这段代码报错main thread is not in main loop
时间: 2023-12-06 10:03:00 浏览: 140
这个错误通常是由于在非主线程中使用了 matplotlib 库的某些功能导致的。为了避免这个错误,您可以在调用 `plt` 绘图函数之前,添加以下两行代码:
```python
import matplotlib
matplotlib.use('Agg')
```
这样就可以将 matplotlib 的后端设置为 "Agg",这是一种不需要图形界面的后端,可以避免在非主线程中使用 matplotlib 函数时出现报错。最终代码应该是这样的:
```python
import matplotlib
matplotlib.use('Agg')
import pandas
import numpy
from scipy import stats
from sklearn.metrics import r2_score
import matplotlib.pyplot as plt
def temp(filename, x, dic):
path = 'excelFile/' + filename
df = pandas.read_excel(path, header=None)
data = []
datax = df.iloc[0].tolist()
datay = df.iloc[1].tolist()
transInt(datax)
transInt(datay)
slope, intercept, r, p, std_err = stats.linregress(datax, datay)
def myfunc(datax):
return slope * datax + intercept
mymodel = list(map(myfunc, datax))
plt.scatter(datax, datay)
plt.plot(datax, mymodel)
print(x)
result = myfunc(int(x))
if r >= 0.7 or r <= -0.7:
count = 2
while count < 6:
mymodel_2 = numpy.poly1d(numpy.polyfit(datax, datay, count))
myline = numpy.linspace(min(datax), max(datay), 100)
r2 = r2_score(datay, mymodel_2(datax))
plt.scatter(datax, datay)
plt.plot(myline, mymodel_2(myline))
result = mymodel_2(int(x))
if r2 >= 0.7 or r2 <= -0.7:
break
plt.savefig('figs/result.png')
dic['Y'] = str(result)
```
这样就可以避免这个报错了。
阅读全文