在Windows上,当我使用pickle模块保存3D matplotlib曲面图并重新加载它们时,这些图缺少任何交互功能,例如能够旋转图或放大图。但是,如果我保存并重新加载2D腌制的matplotlib图,则仍然可以与图进行交互,至少可以使用缩放工具进行交互。以下代码重新创建成功的2D绘图案例。
import matplotlib.pyplot as plt
import numpy as np
import pickle
xs = np.linspace(0, 4*np.pi, 100)
ys = np.sin(xs)
fig, ax = plt.subplots()
ax.plot(xs, ys)
with open("plot.pickle", 'wb') as file:
pickle.dump(fig, file)
plt.show()
plt.close(fig)
with open("plot.pickle", 'rb') as file:
fig = pickle.load(file)
plt.show()
以下代码是一个重现3D绘图问题的小示例。
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pickle
xs = np.linspace(0, 1, 100)
ys = np.linspace(0, 4*np.pi, 100)
zs = np.zeros((100, 100))
for i, amp in enumerate(xs):
for j, phase in enumerate(ys):
zs[j, i] = amp*np.sin(phase)
xs, ys = np.meshgrid(xs, ys)
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
ax.plot_surface(xs, ys, zs)
with open("plot.pickle", 'wb') as file:
pickle.dump(fig, file)
plt.close(fig)
with open("plot.pickle", 'rb') as file:
fig = pickle.load(file)
plt.show()
我可以进行哪些更改,以使我的3D腌制图具有交互式旋转和缩放功能?如果3D腌制图无法实现这种功能,那么它们是否是保存(无需在窗口中最初显示图)并重新加载交互式3D matplotlib曲面图的替代方法?
答案 0 :(得分:0)
我发现不是解决方案,而是解决方法。 解决方法是将绘制r =图形所需的所有数据以及将其绘制到pickle文件中的功能进行保存。
为此,我需要使用dill
代替picke
,如bu @JoshRosen所建议
在他对Is there an easy way to pickle a python function (or otherwise serialize its code)?
创建泡菜:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import dill as pickle
def plotfun(plotdata):
ax = plt.gca()
ax.plot_surface(plotdata['xs'], plotdata['ys'], plotdata['zs'])
xs = np.linspace(0, 1, 100)
ys = np.linspace(0, 4*np.pi, 100)
zs = np.zeros((100, 100))
for j, phase in enumerate(ys):
zs[j, :] = xs*np.sin(phase)
xs, ys = np.meshgrid(xs, ys)
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
plotdata = {'xs': xs, 'ys': ys, 'zs': zs, 'plotfun': plotfun}
plotdata['plotfun'](plotdata)
with open("test.pickle", 'wb') as file:
pickle.dump(plotdata, file)
加载泡菜
import dill as pickle
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
plt.figure().add_subplot(111, projection='3d'),
plotdata = pickle.load(open('test.pickle', 'rb'))
plotdata['plotfun'](plotdata)
plt.show()