Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a figure binary object by matplotlib?

I like to use matplotlib to exhibit science experiment result, and I want to storage those pictures to MongoDB.
Although I had read the matplotlib official document, I can't find any method to get a file-like object can easily storage into GridFS.
A viable solution is to save the figure to a png file, then upload this png file to GridFS. Is there any more succinct method?

like image 742
zhenlingcn Avatar asked Sep 21 '26 19:09

zhenlingcn


1 Answers

I solved this problem.

def plot_fig(file_name):
    x = np.linspace(0, 10, 10)
    y = np.linspace(0, 10, 10)
    plt.plot(x, y)

    from io import BytesIO
    figfile = BytesIO()
    plt.savefig(figfile, format='png')

    fs = GridFS(db)
    try:
        f = fs.new_file(filename=file_name)
        f.write(figfile.getvalue())
    finally:
        f.close()
like image 141
zhenlingcn Avatar answered Sep 24 '26 09:09

zhenlingcn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!