Wie man matplotlib plt.savefig() in einen io.BytesIO-Puffer speichert
Sie können einfach ein io.BytesIO() als ersten Parameter an plt.savefig() übergeben. Beachten Sie, dass format standardmäßig "png" ist, aber Best Practice ist, es explizit anzugeben.
savefig_bytesio.py
# Save plot to BytesIO
bio = io.BytesIO()
plt.savefig(bio, dpi=250, format="png")Vollständiges Beispiel:
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())Ausgabe 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