亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Matplotlib之解決plt.savefig()保存多張圖片有重疊的問題

 更新時間:2023年09月14日 15:15:26   作者:Mic28  
這篇文章主要介紹了Matplotlib之解決plt.savefig()保存多張圖片有重疊的問題,具有很好的參考價值,希望對大家有所幫助,

Python Matplotlib 解決plt.savefig()保存多張圖片有重疊問題

問題描述

在多次調(diào)用plt.savefig()時,出現(xiàn)了保存的圖片有上一個數(shù)據(jù)出現(xiàn)并重疊的現(xiàn)象。

如下圖:

在這里插入圖片描述

部分代碼:

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() 內(nèi)可輸入的參數(shù)為:

  • None: 目前的figure
  • Figure: 給定的Figure實例
  • int: 一個 figure數(shù)
  • str: 一個 figure名字
  • ‘all’: 全部 figures

另外,有時候也會因為沒有關(guān)閉上一個canvas, 導(dǎo)致出現(xiàn)以下問題:

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

參考鏈接:pyplot.close()

matplotlib—plt.savefig存儲高清圖片

1.matplotlib模塊中pyplot的引入

import matplotlib.pyplot as plt

2.保存與顯示

在代碼的順序中,保存需要在顯示的前面

#保存圖片
#bbox_inches='tight'表示指定將圖表多余的空白區(qū)域裁減掉
plt.savefig('test.png', bbox_inches='tight')
#顯示圖片
plt.show()

如果plt.show() 在plt.savefig()前,就會導(dǎo)致保存圖片是空白的情況。

3.保存高清圖片

將保存的圖片后綴進行修改,改為.svg即可。

plt.savefig('test.svg', bbox_inches='tight')
#顯示圖片
plt.show()

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論