Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib savefig() blank - show() isn't

I've browsed the "Questions that may already have your answer", and if they did... I didn't understand it.

I've tried to eliminate as much as I could and simplified my problem down to the following code (my apologies - I'm sure there's a more elegant way of getting a numpy array of all 40s, but this was what I came up with after banging my head....):

import numpy
import matplotlib.pyplot as plt

x=numpy.zeros((500,256))
x+=40
plt.title("Title")
plt.xlabel("Label")
plt.ylabel("Label")
plt.imshow(x,vmin=37.5,vmax=42.5, cmap='spectral')

#save the figure
filename="/xxx/yyy/matplotlibtest.jpg"
plt.savefig(filename)
plt.show()
plt.close()

plt.savefig() returns a very nice image with my labels, axes, and no figure (ie, the rectangle is blank)

plt.show() shows me all of the above with a nice green rectangle where it belongs, in between my axes, as it ought to be. I can manually save this figure to the same directory, and get the result I expect (ie, axes, labels, green rectangle).

I've tried this without the show() or by having the show() call come 2nd, as some questions & answers on here (and elsewhere) seemed to imply that the call order may be the problem.

I've saved out other figures (histograms of the same data) in this code as jpg's, so I know this computer can save as jpg.

I'm not sure what I'm doing wrong with savefig - any suggestions?

Thanks!

like image 904
Topher Hughes Avatar asked Oct 31 '12 23:10

Topher Hughes


1 Answers

By adding:

import matplotlib
matplotlib.use('TkAgg')

in before my call to

import matplotlib.pyplot as plt

I'm able to get everything working happily.

(I don't understand the backends yet, clearly!)

like image 92
Topher Hughes Avatar answered Oct 06 '22 01:10

Topher Hughes