我試圖將一個圖對象保存爲一個pickle文件並稍後從中檢索數據。我練習了一個示例代碼,但是我無法在加載它後從pickle文件中檢索數據。下面是我的代碼醃Matplotlib圖對象檢索數據
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pickle
Fs = 8000
f = 1000
sample =20000
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x/Fs)
plt.figure()
plt.plot(x, y)
plt.xlabel('voltage(V)')
plt.ylabel('sample(n)')
plt.show()
dt=1.0/Fs
winsize=1024
shift=int(winsize/2)
frqlen=shift
datalen=len(y)
FFTdata=np.zeros((0,frqlen))
fftfreq=np.fft.fftfreq(winsize,d=dt)[:frqlen]
for i in range(0,datalen,shift):
xdata=x[i:i+winsize]
if len(xdata)!=winsize:
break
fftdata=np.fft.fft(xdata,winsize)
absdata=np.abs(fftdata)[:frqlen]
logpower=10* np.log(absdata ** 2).reshape((1,len(absdata)))
FFTdata=np.append(FFTdata,logpower,axis=0)
sampleno=np.arange(1,len(FFTdata)+1)
fig,ax=plt.subplots()
FFTdata=FFTdata.T
im=ax.pcolor(sampleno,fftfreq,FFTdata)
cbar=fig.colorbar(im)
fig.show()
pickle.dump(fig,open("dumptrial.p",'wb'))
figure=pickle.load(open("dumptrial.p",'rb'))
figure.show()
data=figure.axes[0].images[0].get_data()
在最後一行data=figure.axes[0].images[0].get_data()
蟒蛇拋出Indexing error: List index out of range
。
Traceback (most recent call last):
File "<ipython-input-9-e9dc466f2abb>", line 1, in <module>
runfile('C:/Users/na.anusuya/Documents/pickletrial.py', wdir='C:/Users/na.anusuya/Documents')
File "C:\Users\na.anusuya\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Users\na.anusuya\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/na.anusuya/Documents/pickletrial.py", line 43, in <module>
data=figure.axes[0].images[0].get_data()
IndexError: list index out of range
有人可以幫助我如何從醃製數字對象中檢索數據嗎?
(I用於該代碼的來源是:https://gist.github.com/demisjohn/883295cdba36acbb71e4 http://fredborg-braedstrup.dk/blog/2014/10/10/saving-mpl-figures-using-pickle/ )
請加入適當縮進到您的代碼。另外,你在if條件中測試的操作是什麼if'len(xdata)<> winsize:' – otayeby