问题描述
在使用matplotlib绘制多张图像时,可能出现两张图像的结果中出现重叠(画布重叠)
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [2, 1, 5, 3, 2]
plt.plot(x, y1)
plt.savefig("1.png")
plt.plot(x, y2)
plt.savefig("2.png")
这种方式保存的图像如下:
- 1.PNG
- 2.PNG
可以发现,我们是想把(x,y1) 和 (x,y2) 分开保存为两张图像,但是最后保存的图像2.PNG中出现了两个线的结果,如果直接plt.show()其实是正常的,这种情况只会出现在保存图像的时候。
解决方法:
每次在绘制图像的时候,声明一个新画布:plt.figure()
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [2, 1, 5, 3, 2]
plt.figure() # 声明一个新画布
plt.plot(x, y1)
plt.savefig("1.png")
plt.figure() # 声明一个新画布
plt.plot(x, y2)
plt.savefig("2.png")
图像如下:
- 1.PNG
- 2.PNG