Search code examples
python-2.7matplotlibcstringio

Matplotlib savefig to cStreamIO then load the data into another Matplotlib plot/fig Python 2.7


Attempting to use matplotlib to write out to an iostream then display that data in another matplotlib plot (started by following: Write Matplotlib savefig to html). For efficiency purposes, I want to avoid writing the image to disk.

Here's the code:

import cStringIO
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt2
import matplotlib.image as mpimg

sio = cStringIO.StringIO()
plt.savefig(sio, format='png')

# I should mention at this point here that the sio object is sent through a 
# pipe between two processes (so it has been pickled)    

imgplt = plt2.imshow(mpimg.imread(sio.getvalue().encode("base64").strip()))
# this line generates the following error.  As well as several variations 
#   including specifying 'png'

The error returned is: IOError: [Errno 22] invalid mode ('rb') or filename: 'iVBORw...followed by a long string with the data from the image'

I looked at the image.py file and it appears to be looking for a filename.

Thanks for taking a look.


Solution

  • imread interpretes the string given to it as filename. Instead one would need to supply a file-like object.

    You would get such file-like object as the buffer itself. However, StringIO may not be well suited. If you use BytesIO, you can directly read in the buffer.

    import io
    import matplotlib.pyplot as plt
    
    plt.plot([1,2,4,2])
    plt.title("title")
    
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    
    imgplt = plt.imshow(plt.imread(buf))
    
    plt.show()