Python Matplotlib: 解决plt.savefig() 保存多张图片有重叠的问题
问题描述:
在多次调用plt.savefig()时,出现了保存的图片有上一个数据出现并重叠的现象。如下图:
部分代码:
import matplotlib.pyplot as plt
def ch_graph(num_clusters, ch_score, filepath, method, module):
# Plot ch graph
plt.plot(num_clusters, ch_score, 'bx-')
plt.xlabel('Number of cluster')
plt.ylabel('Calinski-Harabasz Score')
plt.title('Calinski-Harabasz Score against Number of Cluster')
plt.grid(True)
filename = 'ch_graph_one.png'
folder = 'Picture/'
ch_filepath = filepath + '/' + folder + filename
plt.savefig(ch_filepath)
def elbow_graph(num_clusters, Sum_of_squared_distances, filepath, method, module):
# Plot ch graph
plt.plot(num_clusters, Sum_of_squared_distances, 'bx-')
plt.xlabel('Number of cluster')
plt.ylabel('Sum of squared dist')
plt.title('Sum of squared dist against Number of Cluster')
plt.grid(True)
filename = 'elbow_graph_one.png'
folder = 'Picture/'
elbow_filepath = filepath + '/' + folder + filename
plt.savefig(elbow_filepath)
解决方法:
在plt.savefig()
的下一行加上plt.close()
就可以了。对于使用seaborn
来绘制的图片,也同样使用plt.close()
。
plt.close()
内可输入的参数为:
- None: 目前的figure
- Figure: 给定的Figure实例
- int: 一个 figure数
- str: 一个 figure名字
- ‘all’: 全部 figures
另外,有时候也会因为没有关闭上一个canvas, 导致出现以下问题:
fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors
参考链接:
pyplot.close()
版权声明:本文为qq_39560620原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。