如何将 matplotlib plt.savefig() 保存到 io.BytesIO 缓冲区
你可以将 io.BytesIO() 作为第一个参数传递给 plt.savefig()。注意 format 默认为 "png",但最佳做法是显式指定它。
savefig_bytesio.py
# Save plot to BytesIO
bio = io.BytesIO()
plt.savefig(bio, dpi=250, format="png")完整示例:
savefig_bytesio.py
#!/usr/bin/env python3
import numpy as np
import io
import matplotlib.pyplot as plt
# Generate data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
# Plot data
plt.plot(x, y)
# Save plot to BytesIO
bio = io.BytesIO()
plt.savefig(bio, dpi=250, format="png")
# Cleanup plot
plt.close(plt.gcf())
plt.clf()
# Write BytesIO to file
with open("plot.png", "wb") as f:
f.write(bio.getvalue())输出 plot.png:

Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow