Python?Matplotlib中使用plt.savefig存儲圖片的方法舉例
前言
plt.show()展示圖片的時候,截圖進行保存,圖片不是多么清晰
如何保存高清圖也是一知識點
函數(shù)包名:import matplotlib.pyplot as plt
主要功能:
保存繪制數(shù)據(jù)后創(chuàng)建的圖形。使用此方法可以將創(chuàng)建的圖形保存
函數(shù)源碼:(根據(jù)需要進行選擇)
savefig(fname, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None)
參數(shù)解釋:
參數(shù) | 描述 |
---|---|
fname | 指定格式圖片或者指定文件位置 |
dpi | 畫質(zhì) |
facecolor 和 edgecolor | 默認為白色 |
Orientation | 橫向或者縱向 |
papertype | 紙張類型 |
format | 如png、pdf |
transparent | 圖片背景透明 |
bbox_inches | 圖表多余的空白區(qū)去除 |
pad_inches | 保存圖形周圍填充 |
正常保存:plt.savefig("xx.png")
,也可以svg的格式進行保存
保存的時候需要plt.show()在plt.savefig()之后,順序顛倒會出現(xiàn)圖片為空白。
當前文件保存:
注意事項:
- 如果plt.show() 在plt.savefig()前,就會導致保存圖片是空白的情況。
- window的路徑讀取,需要反斜杠
要把所有的參數(shù)用上,可以用在直方圖上
import matplotlib.pyplot as plt x =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] plt.hist(x) plt.savefig("squares1.png", bbox_inches ="tight", pad_inches = 1, transparent = True, facecolor ="g", edgecolor ='w', orientation ='landscape') plt.show()
截圖如下:
補充:解決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
另外,有時候也會因為沒有關閉上一個canvas, 導致出現(xiàn)以下問題:
fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors
總結
到此這篇關于Python Matplotlib中使用plt.savefig存儲圖片的文章就介紹到這了,更多相關Matplotlib用plt.savefig存儲圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實現(xiàn)提取圖片中顏色并繪制成可視化圖表
今天小編來為大家分享一個有趣的可視化技巧,就是如何利用Python語言實現(xiàn)從圖片中提取顏色然后繪制成可視化圖表,感興趣的可以嘗試一下2022-07-07python實現(xiàn)一行輸入多個整數(shù)并排序輸出
這篇文章主要介紹了python實現(xiàn)一行輸入多個整數(shù)并排序輸出方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02pytorch使用voc分割數(shù)據(jù)集訓練FCN流程講解
這篇文章主要介紹了pytorch使用voc分割數(shù)據(jù)集訓練FCN流程,圖像分割發(fā)展過程也經(jīng)歷了傳統(tǒng)算法到深度學習算法的轉變,傳統(tǒng)的分割算法包括閾值分割、分水嶺、邊緣檢測等等2022-12-12