我正在尝试在循环中创建多个图表。我创建的图表每次都会自动保存在不同的文件夹中。这是代码:
x = [2,4,6]
y = [1,2,3]
for i in x:
for j in y:
outputpath = './home/' + 'folder'+ str(i) + str(j)
if not path.exists(outputpath):
try:
os.makedirs(outputpath)
except OSError:
print("Creation failed")
else:
print("Successfully created")
a = np.random.rand(1000)
b = np.random.rand(20000)
#Plotting a
plt.scatter((range(0,len(a))),a)
path1 = outputpath + '/' + 'a' + '.png'
plt.savefig(path1)
#Plotting b
plt.scatter((range(0,len(b))),b)
path2 = outputpath + '/' + 'b' + '.png'
plt.savefig(path2)
图表被保存在相应的文件夹中。但是每次生成新的图表时,都会覆盖旧的图表。如下图所示。该图表是为i = 2和j = 2创建的。该图表保存在./home/folder22中,并且也被之前文件夹中生成的图表覆盖了。我该如何避免这种情况发生? 更新:我相信每次绘图之前都必须使用plt.figure()?