【发布时间】:2016-12-08 11:01:30
【问题描述】:
我希望找到一种方法来优化以下情况。我有一个用 matplotlib 的 imshow 创建的大型等高线图。然后我想使用这个等高线图来创建大量 png 图像,其中每个图像都是通过改变 x 和 y 限制以及纵横比的轮廓图像的一小部分。
所以循环中没有绘图数据发生变化,只有轴限制和纵横比在每个 png 图像之间发生变化。
以下 MWE 在“figs”文件夹中创建了 70 张 png 图像,展示了简化的想法。 fig.savefig('figs/'+filename) 占用了大约 80% 的运行时间。
我研究了以下内容,但没有提出改进意见:
-
matplotlib的替代方案,专注于速度 - 我一直在努力寻找具有类似要求的等高线/曲面图的任何示例/文档 - Multiprocessing -- 我在这里看到的类似问题似乎需要在循环中调用
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))
【问题讨论】:
标签: python performance matplotlib png imshow