我有一个循环加载并绘制一些数据,如下所示:
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/