python - Matplotlib:检查空图

标签 python python-3.x matplotlib figure

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

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/plt/the figure/the axis 无论图形/轴是否完全为空。就像是
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()

最佳答案

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

if ax.lines:

如果它们是使用 scatter() 绘制的反而:
if ax.collections:

关于python - Matplotlib:检查空图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52386747/

相关文章:

python : Postfix stdin

python - 继承Python中同名的类

python-3.x - 在python中创建从a到b的整数列表

python - "if"语句查找剩余数字并附加到 csv 列表中

python - 如何在 pyaudio 播放 .wav 文件时继续计算

python - 远程 ipython 内核不显示图

python - 如何将这个带有二进制数据的 curl 写入 python?

python - 这个字符串标准化器 Python 片段有什么问题?

python - python 2.7 中对数对数刻度的最佳拟合线

python - 从记录 ndarray 中选择行范围