我有一个循环加载并绘制一些数据,如下所示:
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
/数字/轴是否图形/轴完全是空的。就像是
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()
用fig.get_axes()
检查图中是否有任何轴用于您的目的?
fig = plt.figure()
if fig.get_axes():
# Do stuff when the figure isn't empty.
要检查斧头是否有使用plot()
绘制的数据:
if ax.lines:
如果他们使用scatter()
而不是:
if ax.collections:
正如你所说,显而易见的解决方案是在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()