日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python?Matplotlib中使用plt.savefig存儲圖片的方法舉例_python

作者:碼農研究僧 ? 更新時間: 2023-05-07 編程語言

前言

plt.show()展示圖片的時候,截圖進行保存,圖片不是多么清晰

如何保存高清圖也是一知識點

函數包名:import matplotlib.pyplot as plt

主要功能:

保存繪制數據后創建的圖形。使用此方法可以將創建的圖形保存

函數源碼:(根據需要進行選擇)

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)

參數解釋:

參數 描述
fname 指定格式圖片或者指定文件位置
dpi 畫質
facecolor 和 edgecolor 默認為白色
Orientation 橫向或者縱向
papertype 紙張類型
format 如png、pdf
transparent 圖片背景透明
bbox_inches 圖表多余的空白區去除
pad_inches 保存圖形周圍填充

正常保存:plt.savefig("xx.png"),也可以svg的格式進行保存

保存的時候需要plt.show()在plt.savefig()之后,順序顛倒會出現圖片為空白。

當前文件保存:

注意事項:

  • 如果plt.show() 在plt.savefig()前,就會導致保存圖片是空白的情況。
  • window的路徑讀取,需要反斜杠

要把所有的參數用上,可以用在直方圖上

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() 保存多張圖片有重疊的問題

問題描述:

在多次調用plt.savefig()時,出現了保存的圖片有上一個數據出現并重疊的現象。如下圖:

部分代碼:

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

總結

原文鏈接:https://blog.csdn.net/weixin_47872288/article/details/128739356

欄目分類
最近更新