3

Here are my visualization codes:

f, ax = plt.subplots(1, 2)
for i, img in enumerate([img1, img2]):    
    grads = # my visualization codes
# visualize grads as heatmap
ax[i].imshow(grads, cmap='jet')

How could I save whatever was shown using imshow here? Any advice is greatly appreciated!

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
shenglih
  • 879
  • 2
  • 8
  • 18

1 Answers1

5

Saving the whole figure is simple, just use the savefig function:

f.savefig('filename.png')

There are a number of file formats you can save to, and these are usually inferred correctly from the extension of the filename. See the documentation for more information.

The savefig function takes an argument bbox_inches, which defines the area of the figure to be saved. To save an individual subplot to file you can use the bounding box of the subplot's Axes object to calculate the appropriate value.

Putting it all together your code would look something like this:

f, ax = plt.subplots(1, 2)
for i, img in enumerate([img1, img2]):    
    grads = # my visualization codes
    # visualize grads as heatmap
    ax[i].imshow(grads, cmap='jet')

    # Save the subplot.
    bbox = ax[i].get_tightbbox(f.canvas.get_renderer())
    f.savefig("subplot{}.png".format(i),
              bbox_inches=bbox.transformed(f.dpi_scale_trans.inverted()))

# Save the whole figure.
f.savefig("whole_figure.png")
mostlyoxygen
  • 981
  • 5
  • 14
  • This answer works, but in my case all the labels, legends, etc are shifted so that they overlap in the saved images. They do that also in the `show`n plot, unless I maximize the window. Using [fig.set_size_inches(16,9)](https://stackoverflow.com/questions/10041627/how-to-make-pylab-savefig-save-image-for-maximized-window-instead-of-default) and the optional argument in `savefig` `dpi=300` fixed that for me. – lucidbrot Mar 03 '21 at 10:59