Matplotlib: Check for empty plot

Viewed 8203

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()
3 Answers

To check if an ax has data drawn using plot():

if ax.lines:

If they were drawn using scatter() instead:

if ax.collections:

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.

As you say, the obvious solution is to include saving within the if statement

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')  # <-- indentation here
    plt.close()

Else, it will depend on what "empty" really means. If it is that a figure does not contain any axes,

for filename in filenames:
    fig = plt.figure()
    if os.path.exists(filename):
        x, y = np.loadtxt(filename, unpack=True)
        plt.plot(x, y)
    if len(fig.axes) > 0:  
        plt.savefig(filename + '.png')
    plt.close()

However those are somehow workarounds. I think you really want to perform the logic step yourself.

for filename in filenames:
    plt.figure()
    save_this = False
    if os.path.exists(filename):
        x, y = np.loadtxt(filename, unpack=True)
        plt.plot(x, y)
        save_this = True
    if save_this:
        plt.savefig(filename + '.png')
    plt.close()
Related