【问题标题】:Matplotlib: Check for empty plotMatplotlib:检查空图
【发布时间】:2019-02-22 12:00:18
【问题描述】:

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

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

现在,如果文件不存在,则不会加载或绘制数据,但仍会保存(空)图形。在上面的例子中,我可以通过在if 语句中包含所有plt 调用来纠正这个问题。我的实际用例涉及更多,因此我正在寻找一种方法来询问matplotlib/plt/图形/轴是否图形/轴完全为空。类似的东西

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

【问题讨论】:

  • 请注意,从来没有一个完全空的数字。所以你可能想更彻底地定义“空”。此外,您可能拥有的有关非空数字可能包含的任何信息可能会有所帮助,例如如果你知道例如如果一个图形被认为是“非空的”,它将在一个轴上包含一条线,或者两个图像或类似的,这将允许针对特定的那些进行测试。

标签: python python-3.x matplotlib figure


【解决方案1】:

检查斧头是否有使用plot()绘制的数据:

if ax.lines:

如果它们是使用scatter() 绘制的:

if ax.collections:

【讨论】:

  • 如果使用imshow 绘制,请检查ax.get_images() 的列表输出。在实际操作中,您可以通过if bool(ax.get_images()): 使用它
  • @Aelius 绝对是。我们可以检查许多列表。我们还可以检查if ax.hasData(),如果找到至少一位艺术家(任何类型),则返回 true。
  • 太棒了!我不知道... matplotlib.axes 页面没有很好地记录有关方法的内容
【解决方案2】:

检查图中是否有带有fig.get_axes() 的轴是否适合您的目的?

fig = plt.figure()
if fig.get_axes():
    # Do stuff when the figure isn't empty.

【讨论】:

  • 如果您将 if 语句放在 fig = plt.figure 之后,您的代码中的 if 语句将始终得到满足
  • 你是对的,我在那里输入了错误的not。对不起!它现在应该可以工作了。
【解决方案3】:

正如您所说,显而易见的解决方案是在 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()

【讨论】:

  • 在最后一种情况下,假设 x 和 y 为空(文件中没有数据),仍然会生成一个空白数字,save_this 将变为 True,因此该数字将是保存。还是我在 OP 的问题中遗漏了什么?
  • if fig.axes: 有点 Pythonic。
  • @Bazingaa 空文件会引发错误。但这就是重点:我们不知道在什么条件下保存或不保存人物,因此 OP 想要根据自己的喜好设置这个条件。
  • @ImportanceOfBeingErnest:如果我尝试保存一个空图,我不会收到任何错误。但是要引发错误,需要对输入数据形状/长度进行一些检查。无论如何,由于OP的问题不是很清楚,因此没有必要进一步澄清。感谢您的回复
  • @Bazingaa 如果filename 是一个空文件,那么x, y = np.loadtxt(filename, unpack=True) 行会引发错误。所以要么文件存在并且里面有一些数据,然后图形被保存,或者文件不存在,那么它不保存。如果文件可能为空,则代码无论如何都需要看起来不同(可能使用 try/except)。
猜你喜欢
  • 2012-08-16
  • 2014-05-20
  • 2017-11-20
  • 1970-01-01
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多