我正在尝试将图形对象保存为pickle文件,并稍后从中检索数据。我练习了示例代码但是在加载后我无法从pickle文件中检索数据。以下是我的代码
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()
python抛出一个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
有人可以帮我解决如何从腌制的图形对象中检索数据吗?
(我用于此代码的来源是:https://gist.github.com/demisjohn/883295cdba36acbb71e4 http://fredborg-braedstrup.dk/blog/2014/10/10/saving-mpl-figures-using-pickle/ )
答案 0 :(得分:1)
酸洗没有问题。
只有figure.axes[0].images
是零长度。
pcolor返回PolyCollection(matplotlib page)
通过运行
可以看到存在PolyCollectionprint(figure.axes[0].get_children())
现在您可以通过
访问该对象pycol = None
for obj in figure.axes[0].get_children():
if isinstance(obj, matplotlib.collections.PolyCollection):
pycol = obj
break
print(pycol)