Python Matplotlib: 解决plt.savefig() 保存多张图片有重叠的问题

Python Matplotlib: 解决plt.savefig() 保存多张图片有重叠的问题


问题描述:
在多次调用plt.savefig()时,出现了保存的图片有上一个数据出现并重叠的现象。如下图:
Python Matplotlib: 解决plt.savefig() 保存多张图片有重叠的问题_第1张图片

部分代码:

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()内可输入的参数为:

  1. None: 目前的figure
  2. Figure: 给定的Figure实例
  3. int: 一个 figure数
  4. str: 一个 figure名字
  5. ‘all’: 全部 figures

另外,有时候也会因为没有关闭上一个canvas, 导致出现以下问题:

fig.canvas.draw_idle()   # need this if 'transparent=True' to reset colors

参考链接:
pyplot.close()

你可能感兴趣的:(Python Matplotlib: 解决plt.savefig() 保存多张图片有重叠的问题)