RMRiver
RMRiver

Reputation: 645

Matplotlib - export figure to png in memory buffer

Is it possible to export a matplotlib figure as a png to a bytes type? Here is the code I currently have:

def import_chart(df, x_label, y_label, title):
    fig, ax = plt.subplots()
    ax.plot(data[x_label], data[y_label])

    ax.set(xlabel=x_label, ylabel=y_label,
           title=title)
    image_name = 'test.png'

    fig.savefig(image_name)
    f = open(image_name, 'rb+')
    img = f.read()
    f.close()
    os.remove(image_name)

    return img

The image that is returned is of type class 'bytes'. I would like to avoid saving to the hard drive and reading it again. Something like this:

def import_chart(self, x_label, y_label, title):
    fig, ax = plt.subplots()
    data = self.file_data.get_column([x_label,y_label])
    ax.plot(data[x_label], data[y_label])

    ax.set(xlabel=x_label, ylabel=y_label,
           title=title)
    buffer = buffer.to_buffer(fig.savefig(), format='png')
    img = buffer.read()
    return img

Upvotes: 3

Views: 2277

Answers (1)

Rickey
Rickey

Reputation: 524

I've been using this to render matplotlib images from a web server:

import base64
from io import BytesIO

...

buffer = BytesIO()
plt.savefig(buffer, format='png')
buffer.seek(0)
image_png = buffer.getvalue()
buffer.close()
graphic = base64.b64encode(image_png)
graphic = graphic.decode('utf-8')

return graphic

Upvotes: 4

Related Questions