Matplotlib: Check for empty plot

jmd_dk

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()
Denziloe

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.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事