Can anyone tell me how I can save a Matplotlib chart to a temporary file I create using
tempfile.NamedTemporaryFile()
?
I can't use the Matplotlib's default savefig('hardcoded_file_path') method since I'm in a REST service and I need to control the path so I can delete the temp file when done.
Thank you in advance.
import random
import os
from tempfile import NamedTemporaryFile
import matplotlib.pyplot as plt
from PIL import Image
plt.hist([random.random() for _ in range(100)])
with NamedTemporaryFile("r+b", delete=True) as fd:
# delete is by default True
# the if you don't set it, it will delete the file
# after leaving the with block
plt.savefig(fd)
# seeking back to position 0
# allowed by r+
fd.seek(0)
# show the image from temporary file with PILLOW
Image.open(fd).show()
# Image is shown (window opens)
# but then directly the block is left and the NamedTemporaryFile is deleted
print(fd.name, end=" ")
if os.path.exists(fd.name):
print("still exists.")
else:
print("was deleted.")
You should read the documentation of
NamedTemporaryFile.
Edit:
plt.savefig first argument could be a str or path-like object or a file-like object.
fname : str or path-like or binary file-like
A path, or a Python file-like object, or
possibly some backend-dependent object such as
`matplotlib.backends.backend_pdf.PdfPages`.
This allows also the use of FakeFiles like io.BytesIO.
import random
import io
import matplotlib.pyplot as plt
from PIL import Image
plt.hist([random.random() for _ in range(100)])
file_like = io.BytesIO()
plt.savefig(file_like)
file_like.seek(0)
Image.open(file_like).show()