I am creating a plot using the following code, and saving it to a path. However, the plot opens a new window without me explicitly calling plt.show()
. Does anyone know how to stop the window opening?
arr1 = np.random.rand(150,500)
arr2 = np.random.rand(150,500)
fig = plt.figure()
a=fig.add_subplot(1,2,1)
imgplot = plt.imshow(arr1)
a.set_title('Image 1')
a.xaxis.set_visible(False)
a.yaxis.set_visible(False)
a=fig.add_subplot(2,2,1)
imgplot = plt.imshow(arr2)
a.set_title('Image 2')
a.xaxis.set_visible(False)
a.yaxis.set_visible(False)
plt.savefig('C:/Users/.../fig.png', bbox_inches='tight')
If I understand your question, what you're trying to do is save the plot without displaying it, correct?
To do that, you need to get a Canvas
where your figure is added and then output that canvas to a binary string, which you save to a file. Something like this should work:
from matplotlib.backends.backend_agg import FigureCanvasAgg
from io import BytesIO
canvas = FigureCanvasAgg(my_figure)
image_content = BytesIO()
canvas.print_png(image_content, dpi=my_dpi_resolution)
# Now image_content has your image data, which you can write to a file:
open("my/file.png", "wb").write(image_content)
# This outputs PNG images but other formats are available (print_jpg or print_tif, for instance).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With