0

super simple question but I've been stuck on it for too long and haven't found anything to help.

Using the following code I generate an image that I can see in spyder, but nevertheless when I call the save function, it saves an empty (all white) image.

x,y = np.meshgrid(xs, ys)
z = np.array(zs)

fig = plt.figure(figsize=(2,8))
plt.pcolormesh(x, y, z.T, cmap='RdYlGn')
plt.colorbar()
plt.show()
plt.savefig('test.png')

this is what I see in the IDE:

enter image description here

this is what gets saved:

enter image description here

ItsAnApe
  • 31
  • 1
  • 4

1 Answers1

2

You need to save the image before showing it. Instead of

plt.show()
plt.savefig('test.png')

you need

plt.savefig('test.png')
plt.show()

The reason is that after the plot is shown by plt.show() the figure will be removed from the current pyplot state such that what is saved is a new figure without any content.

However, the figure itself is still present. So if you have a figure handle, you may actually use it to save the figure after it has been shown. The following therefore works:

plt.show()
fig.savefig('test.png')
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712