Python Forum
How to save Matplot chart to temp file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to save Matplot chart to temp file?
#1
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.
Reply
#2
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()
Morkus and Gribouillis like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thanks so much! :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Deleting Windows temp folder Raysz 7 405 Apr-02-2024, 12:36 PM
Last Post: Raysz
  Open/save file on Android frohr 0 316 Jan-24-2024, 06:28 PM
Last Post: frohr
  how to save to multiple locations during save cubangt 1 544 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  save values permanently in python (perhaps not in a text file)? flash77 8 1,207 Jul-07-2023, 05:44 PM
Last Post: flash77
  Save and Close Excel File avd88 0 3,021 Feb-20-2023, 07:19 PM
Last Post: avd88
  Matplot / numpy noisy data problem the57chambers 1 693 Feb-09-2023, 03:27 AM
Last Post: deanhystad
  How to read csv file update matplotlib column chart regularly SamLiu 2 1,059 Jan-21-2023, 11:33 PM
Last Post: SamLiu
  Save multiple Parts of Bytearray to File ? lastyle 1 941 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  Error when running a matplot lib example aurelius_nero 3 6,864 Apr-24-2022, 01:24 PM
Last Post: Axel_Erfurt
Sad Want to Save Print output in csv file Rasedul 5 10,911 Jan-11-2022, 07:04 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020