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)文章
Python GUI Tkinter簡單實現(xiàn)個性簽名設(shè)計
這篇文章主要為大家詳細介紹了Python GUI Tkinter簡單實現(xiàn)個性簽名設(shè)計,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06
Python實現(xiàn)將Excel某范圍單元格內(nèi)容截圖
Openpyxl是一個強大的Python庫,主要用于讀取、寫入和操作Excel文件,本文將使用Openpyxl實現(xiàn)將Excel某范圍單元格內(nèi)容截圖,感興趣的可以了解下2024-11-11
在 Python 應(yīng)用中使用 MongoDB的方法
這篇文章主要介紹了在 Python 應(yīng)用中使用 MongoDB的方法,需要的朋友可以參考下2017-01-01
關(guān)于pyqt5控件自適應(yīng)窗口超詳細知識點匯總
這篇文章主要介紹了關(guān)于pyqt5控件自適應(yīng)窗口超詳細知識點匯總,有了布局,再在布局中放置各種控件,我們就能讓控件實現(xiàn)自適應(yīng)的效果,需要的朋友可以參考下2023-03-03
利用Pycharm + Django搭建一個簡單Python Web項目的步驟
這篇文章主要介紹了利用Pycharm + Django搭建一個簡單Python Web項目的步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10

