Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving file object using matplotlib savefig, creating tar file from multiple svg figures

I have created multiple figures using python with matplotlib. PyQt5 is used as a backend to display the figures. I am saving the figures in svg format using savefig.

My problem is that I would like to create a single zip file containing all of the svg files. A simplified version of what I have is:

import matplotlib
figure = matplotlib.figure.Figure(dpi=72)
canvas = matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg(figure)
axes = figure.add_axes((0.1, 0.15, 0.85, 0.8))
axes.plot(data)
# Do all of that three times to give me three separate figures
# (let's call them figure, figure1 and figure2)

Now I can save each figure using

figure.savefig(filename, format='svg')
figure1.savefig .....

But I would actually like to have something like

fileobject = figure.savefig(format='svg')

where I could use tarfile module to compress and store all fileobjects in a single archive. My current workaround is to save the files, read them and use those objects to create the tar file and deleting the originals afterwards. Having a more direct way to do this would be nice...

like image 498
bgro Avatar asked Oct 28 '25 08:10

bgro


1 Answers

you can use a buffered stream to save your file to. Something like:

import io

fileobject1 = io.BytesIO()
figure1.savefig(fileobject1, format='svg')

fileobject2 = io.BytesIO()
figure2.savefig(fileobject2, format='svg')

etc.

like image 150
tmdavison Avatar answered Oct 30 '25 08:10

tmdavison



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!