Issue
I have a loop which loads and plots some data, something like this:
import os
import numpy as np
import matplotlib.pyplot as plt
for filename in filenames:
plt.figure()
if os.path.exists(filename):
x, y = np.loadtxt(filename, unpack=True)
plt.plot(x, y)
plt.savefig(filename + '.png')
plt.close()
Now, if the file does not exist, the data is not loaded or plotted but an (empty) figure is still saved. In the above example I could correct for this simply by including all of the plt
calls inside of the if
statement. My real use case is somewhat more involved, and so I am in search for a way to ask matplotlib
/plt
/the figure/the axis whether or not the figure/axis is completely empty or not. Something like
for filename in filenames:
plt.figure()
if os.path.exists(filename):
x, y = np.loadtxt(filename, unpack=True)
plt.plot(x, y)
if not plt.figure_empty(): # <-- new line
plt.savefig(filename + '.png')
plt.close()
Solution
Does checking whether there are any axes in the figure with fig.get_axes()
work for your purposes?
fig = plt.figure()
if fig.get_axes():
# Do stuff when the figure isn't empty.
Answered By - Denziloe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.