如何将 matplotlib 图保存为 .png 文件

ABa*_*Lab 4 python plot matplotlib python-3.x

我有一段代码是从工作中的合作者那里获得的。这段代码生成如下图所示的图。 绘图的示例图像

它通过引用另一段代码中的另一个函数来实现这一点;我不想以任何方式改变这一点。

我想做的是编写一段代码,将该图保存为 png 文件,即我正在寻找一个函数,我可以将另一个函数作为变量,将其保存为 png/jpeg 文件。

代码:

这是代码:

for file in files:
 import matplotlib.pyplot as plt
 connection = sqlite3.connect( file )
 animalPool = AnimalPool( )
 animalPool.loadAnimals( connection )

# show the mask of animals at frame 300


 animalPool.showMask( 701 )
Run Code Online (Sandbox Code Playgroud)

它正在调用以下函数:

    def showMask(self, t ):
    '''
    show the mask of all animals in a figure
    '''

    fig, ax = plt.subplots()
    ax.set_xlim(90, 420)
    ax.set_ylim(-370, -40)

    for animal in self.getAnimalList():                    
        mask = animal.getBinaryDetectionMask( t )
        mask.showMask( ax=ax )

    plt.show()
Run Code Online (Sandbox Code Playgroud)

我已经尝试过 matplotlib“savefig”功能,但这只是保存空白图像。

我对编码非常陌生,并且正在尝试即时学习,所以如果这个问题措辞或解释得不好,请让我知道什么是令人困惑的,因为我也在学习如何提出有关此类事情的问题。

Imp*_*est 6

生成 matplotlib 绘图的函数应将图形或轴作为输入,并且仅在需要时选择性地创建这些图形或轴。他们应该返回创建的对象以供进一步使用。最后,他们不应致电plt.show(),或者如果必须的话,提供退出选项。例如,对于单轴绘图函数,它可能看起来像

def plottingfunction(*arguments, ax=None, show=True):
    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.figure

    # do something with fig and ax here, e.g.
    line, = ax.plot(*arguments)

    if show:
        plt.show()

    return fig, ax, line
Run Code Online (Sandbox Code Playgroud)

如果您遵循这种结构,则在调用该函数后可以轻松执行您需要执行的任何操作

fig, _, _ = plottingfunction([1,2,3], [3,2,4], show=False)
fig.savefig("myplot.png")
plt.show()
Run Code Online (Sandbox Code Playgroud)