Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a matplotlib plot from opening a window (plt.show() not called)

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')
like image 959
Ricky Avatar asked Nov 08 '22 17:11

Ricky


1 Answers

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).
like image 125
Juan Carlos Coto Avatar answered Nov 14 '22 21:11

Juan Carlos Coto