问题描述
我正在使用matplotlib创建几个pdf绘图,其中包括400个子图.每个只有5个数据点.好的计算机上需要420秒才能保存5张pdf图片.有什么方法可以优化代码,或者对于matplotlib来说是正常的吗?
I am creating a couple of pdf plots with matplotlib which is composed of 400 subplots. Each one has only 5 data points. It takes 420 s on a good computer to save 5 pdf picture. Is there any way to optimize the code or it is just normal for matplotlib?
用于绘制的代码部分:
plot_cnt = 1
for k in np.arange(K_min, K_max + 1):
for l in np.arange(L_min, L_max + 1):
ax = plt.subplot(grid[0], grid[1], plot_cnt)
plot_cnt += 1
plt.setp(ax, 'frame_on', False)
ax.set_ylim([-0.1, 1.1])
ax.set_xlabel('K={},L={}'.format(k, l), size=3)
ax.set_xlim([-0.1, 4.1])
ax.set_xticks([])
ax.set_yticks([])
ax.grid('off')
ax.plot(np.arange(5), (data['S1']['Azimuth'][:, k - 1, l + offset_l] + \
data['S1']['Delta Speed'][:, k - 1, l + offset_l] + \
data['S1']['Speed'][:, k - 1, l + offset_l]) / 3,
'r-o', ms=1, mew=0, mfc='r')
ax.plot(np.arange(5), data['S2'][case][:, k - 1, l + offset_l],
'b-o', ms=1, mew=0, mfc='b')
plt.savefig(os.path.join(os.getcwd(), 'plot-average.pdf'))
plt.clf()
print 'Final plot created.'
最终图片:
推荐答案
以@rowman所说的内容为基础,您可以在一个轴上完成所有操作(关闭所有刻度线等).像这样:
Building off of what @rowman said, you can do this all in one axes (as you turn off all the ticks etc). Something like:
K_max = 20
K_min = 0
L_max = 20
L_min = 0
ax = plt.subplot(111)
x_offset = 7 # tune these
y_offset = 7 # tune these
plt.setp(ax, 'frame_on', False)
ax.set_ylim([0, (K_max-K_min +1)*y_offset ])
ax.set_xlim([0, (L_max - L_min+1)*x_offset])
ax.set_xticks([])
ax.set_yticks([])
ax.grid('off')
for k in np.arange(K_min, K_max + 1):
for l in np.arange(L_min, L_max + 1):
ax.plot(np.arange(5) + l*x_offset, 5+rand(5) + k*y_offset,
'r-o', ms=1, mew=0, mfc='r')
ax.plot(np.arange(5) + l*x_offset, 3+rand(5) + k*y_offset,
'b-o', ms=1, mew=0, mfc='b')
ax.annotate('K={},L={}'.format(k, l), (2.5+ (k)*x_offset,l*y_offset), size=3,ha='center')
plt.savefig(os.path.join(os.getcwd(), 'plot-average.pdf'))
print 'Final plot created.'
运行大约一两秒.我认为所有时间都花在设置axes
对象上,该对象内部非常复杂.
Runs in about a second or two. I think all of the time is spent setting up the axes
object which are rather complex internally.
这篇关于matplotlib非常慢.正常吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!