python 如何将 matplotlib 图表保存到临时文件?

How to save matplotlib chart to temporary file in python?

我需要将 Matplot 图保存到我控制的临时文件中,因为这段代码将在 python Flask REST 服务中。

我试过这个:

fp = tempfile.NamedTemporaryFile() return_base64 = ""

with fp:
    fp.write(plt.savefig) # THIS IS WRONG....
    with open(fp.name, 'rb') as open_it:
        open_it.seek(0)
        return_base64 = str(base64.b64encode(open_it.read()))
        # strip off leading b and ' and trailing '
        return_base64 = return_base64[2: len(return_base64) - 1]
        open_it.close()
    fp.close()

但是,“fp.write”无法像我上面那样保存 plt.savefig。

我的问题是我正在使用 PRAAT 语音库,但似乎无法在 REST 服务中使用“Sound()”方法。因此,我正在做很多临时文件来解决这个问题。

那么,如何将 matplotib 图写入命名的临时文件?

提前表示感谢。

我正在分享这段代码,它将 jpg 文件存储在我的临时文件夹中

import io 

buf = io.BytesIO()
plt.savefig(buf, format="jpg")
#print(buf.getvalue()) return bytes of plot 

fp = tempfile.NamedTemporaryFile() 

# print(fp.name) return file name 

with open(f"{fp.name}.jpg",'wb') as ff:
    ff.write(buf.getvalue()) 

buf.close()