我希望找到一种优化以下情况的方法。我使用matplotlib的imshow创建了一个大的等高线图。然后,我想使用这个等高线图创建大量的png图像,其中每个图像都是通过更改x和y限制以及纵横比例从等高线图中获取的一小部分。
因此,在循环中没有绘图数据发生变化,只有轴限制和纵横比例在每个png图像之间发生变化。
以下MWE在“figs”文件夹中创建了70个png图像,演示了简化的想法。约80%的运行时间用于
我尝试了以下方法但没有得到改进:
因此,在循环中没有绘图数据发生变化,只有轴限制和纵横比例在每个png图像之间发生变化。
以下MWE在“figs”文件夹中创建了70个png图像,演示了简化的想法。约80%的运行时间用于
fig.savefig('figs/'+filename)
。我尝试了以下方法但没有得到改进:
- 速度更快的matplotlib替代品--我很难找到类似要求的等高线/表面绘图的任何示例/文档
- 多进程--我在这里看到的类似问题似乎要求在循环内调用
fig = plt.figure()
和ax.imshow
,因为无法将fig和ax序列化。在我的情况下,这将比实现多进程获得的任何速度增益更加昂贵。
import numpy as np
import matplotlib as mpl
mpl.use('agg')
import matplotlib.pyplot as plt
import time, os
def make_plot(x, y, fix, ax):
aspect = np.random.random(1)+y/2.0-x
xrand = np.random.random(2)*x
xlim = [min(xrand), max(xrand)]
yrand = np.random.random(2)*y
ylim = [min(yrand), max(yrand)]
filename = '{:d}_{:d}.png'.format(x,y)
ax.set_aspect(abs(aspect[0]))
ax.set_xlim(xlim)
ax.set_ylim(ylim)
fig.savefig('figs/'+filename)
if not os.path.isdir('figs'):
os.makedirs('figs')
data = np.random.rand(25, 25)
fig = plt.figure()
ax = fig.add_axes([0., 0., 1., 1.])
# in the real case, imshow is an expensive calculation which can't be put inside the loop
ax.imshow(data, interpolation='nearest')
tstart = time.clock()
for i in range(1, 8):
for j in range(3, 13):
make_plot(i, j, fig, ax)
print('took {:.2f} seconds'.format(time.clock()-tstart))