代码之家  ›  专栏  ›  技术社区  ›  jmd_dk

Matplotlib:检查空图

  •  2
  • jmd_dk  · 技术社区  · 6 年前

    我有一个循环,它加载和绘制一些数据,如下所示:

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

    现在,如果文件不存在,则不会加载或绘制数据,但仍会保存一个(空)图形。在上面的示例中,我可以通过包含所有 plt 呼叫的内部 if 语句。我的实际用例有点复杂,因此我正在寻找一种方法来询问 matplotlib / 血小板计数 /图形/轴,无论图形/轴是否完全为空。类似的东西

    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 回复  |  直到 6 年前
        1
  •  1
  •   Denziloe    6 年前

    检查图中是否有轴 fig.get_axes() 为你的目的工作?

    fig = plt.figure()
    if fig.get_axes():
        # Do stuff when the figure isn't empty.
    
        2
  •  4
  •   Guimoute    6 年前

    要检查AX是否使用 plot() :

    if ax.lines:
    

    如果他们是用 scatter() 而是:

    if ax.collections:
    
        3
  •  0
  •   ImportanceOfBeingErnest    6 年前

    正如您所说,显而易见的解决方案是在 if 陈述

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

    否则,它将取决于“空”的真正含义。如果图形不包含任何轴,

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

    然而,这些都是解决办法。我认为你真的想自己执行逻辑步骤。

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