Instead of creating the two interim images like my answer above, an alternative way is to make the two arrays using imshow
, like in the example below.
We will grab the numpy array from the imshow
object using ._rgbacache
, but to generate this you have to display the imshow
object on an axis, hence the fig
and ax
at the beginning.
import numpy as np
import matplotlib.pyplot as plt
# Need to display the result of imshow on an axis
fig=plt.figure()
ax=fig.add_subplot(111)
# Save fig a with one cmap
a=np.random.rand(20,20)
figa=ax.imshow(a,cmap='jet')
# Save fig b with a different cmap
b=np.random.rand(20,20)
figb=ax.imshow(a,cmap='copper')
# Have to show the figure to generate the rgbacache
fig.show()
# Get the array of data
figa=figa._rgbacache
figb=figb._rgbacache
# Stitch the two arrays together
figc=np.concatenate((figa,figb),axis=1)
# Save without a cmap, to preserve the ones you saved earlier
plt.imsave('figc.png',figc,cmap=None)
EDIT:
To do this with imsave
and a file-like object, you need cStringIO
:
import numpy as np
import matplotlib.pyplot as plt
from cStringIO import StringIO
s=StringIO()
t=StringIO()
# Save fig a with one cmap to a StringIO instance. Need to explicitly define format
a=np.random.rand(20,20)
plt.imsave(s,a,cmap='jet',format='png')
# Save fig b with a different cmap
b=np.random.rand(20,20)
plt.imsave(t,b,cmap='copper',format='png')
# Return to beginning of string buffer
s.seek(0)
t.seek(0)
# Get the array of data
figa=plt.imread(s)
figb=plt.imread(t)
# Stitch the two arrays together
figc=np.concatenate((figa,figb),axis=1)
# Save without a cmap, to preserve the ones you saved earlier
plt.imsave('figc.png',figc,cmap=None)