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?
Asked
Active
Viewed 1,595 times
1

HZ-VUW
- 842
- 9
- 20
-
1Something like https://stackoverflow.com/questions/31492525/converting-matplotlib-png-to-base64-for-viewing-in-html-template – ImportanceOfBeingErnest Jul 26 '19 at 17:30
1 Answers
1
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()

HZ-VUW
- 842
- 9
- 20