欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

問(wèn)題描述

在多次調(diào)用plt.savefig()時(shí),出現(xiàn)了保存的圖片有上一個(gè)數(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() 就可以了。

對(duì)于使用 seaborn 來(lái)繪制的圖片,也同樣使用 plt.close() 。

plt.close() 內(nèi)可輸入的參數(shù)為:

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

另外,有時(shí)候也會(huì)因?yàn)闆](méi)有關(guān)閉上一個(gè)canvas, 導(dǎo)致出現(xiàn)以下問(wèn)題:

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

參考鏈接:pyplot.close()

matplotlib—plt.savefig存儲(chǔ)高清圖片

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()前,就會(huì)導(dǎo)致保存圖片是空白的情況。

3.保存高清圖片

將保存的圖片后綴進(jìn)行修改,改為.svg即可。

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

總結(jié)

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

相關(guān)文章

最新評(píng)論