I'm using matplotlib to create a figure with many small subplots (something like 4 rows, 8 columns). I've tried a few different ways, and the fastest that I can get matplotlib to make the axes is ~2 seconds. I saw this post about just using one axes object to display many small images, but I would like to be able to have ticks and titles on the axes. Is there any way to speed this process up, or does making axes in matplotlib just take a reasonably long time?
Here is what I have tried so far:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import time
fig = plt.figure(figsize=(10,6))
plt.clf(); t = time.time()
grid = ImageGrid(fig, 111,
nrows_ncols = (4, 8))
print 'Time using ImageGrid: %.2f seconds'%(time.time()-t)
plt.clf(); t = time.time()
axes = plt.subplots(4,8)
print 'Time using plt.subplots: %.2f seconds'%(time.time()-t)
plt.clf(); t = time.time()
axes = []
for row in range(0,4):
for col in range(1,9):
ax = plt.subplot(4,8,row*8+col)
axes.append(ax)
print 'Time using ptl.subplot loop: %.2f seconds'%(time.time()-t)
output:
Time using ImageGrid: 4.25 seconds
Time using plt.subplots: 2.11 seconds
Time using ptl.subplot loop: 2.34 seconds
Taking Joe Kington's suggestion, I tried to pickle the figure and axes so that I would at least not need to create them every time that I run the script. However, loading the file actually takes longer:
import matplotlib.pyplot as plt
import pickle
import time
t = time.time()
fig,axes = plt.subplots(4,8,figsize=(10,6))
print 'Time using plt.subplots: %.2f seconds'%(time.time()-t)
pickle.dump((fig,axes),open('fig.p','wb'))
t = time.time()
fig,axes = pickle.load(open('fig.p','rb'))
print 'Time to load pickled figure: %.2f seconds'%(time.time()-t)
output:
Time using plt.subplots: 2.01 seconds
Time to load pickled figure: 3.09 seconds