How to matplotlib plt.savefig() to a io.BytesIO buffer
You can just pass a io.BytesIO()
to plt.savefig()
as first parameter. Note that format
defaults to "png"
, but best practice is to explicitly specify it.
# Save plot to BytesIO
bio = io.BytesIO()
plt.savefig(bio, dpi=250, format="png")
Full example:
#!/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())
Output plot.png
: