【问题标题】:How to overwrite `savefig` method so that it can unpack a tuple如何覆盖`savefig`方法以便它可以解包元组
【发布时间】:2021-04-22 06:04:27
【问题描述】:

我正在对一段代码进行最小扩展。

我有一个 make_fig 函数,它过去只生成一个图形,在许多其他函数中我将其称为 fig,然后将其保存为 fig.savefig

在扩展中,make_fig 现在返回一个 元组 数字。所以,为了保存它们,我现在需要类似的东西:

fig = make_fig

for f in fig:
   f.savefig

我希望有一个更优雅的解决方案,不需要在出现 make_fig 的任何地方添加 for 循环。

如果amatplotlib.pytplot 实例,我能否以某种方式修改a.savefig 方法使其正常工作,如果它是元组,则执行上述for 循环?

MWE 下面。

d = 1 是“旧”代码,d=2 是我要添加的扩展名。

import matplotlib.pyplot as plt 

def make_fig(d):
    if d==1:
        fig, ax = plt.subplots(1)
    elif d==2:
        fig1, ax = plt.subplots(1)
        fig2, ax = plt.subplots(1)
        fig = (fig1, fig2)
    else:
        raise Exception('error')
    return fig

d=2
fig = make_fig(d)
fig.savefig('hello.png')

【问题讨论】:

    标签: python savefig


    【解决方案1】:

    只需实现您自己的savefig 函数即可处理这两种情况。

    from collections.abc import Iterable
    
    def savefig(filename, fig):
        if not isinstance(fig, Iterable):
            fig = (fig,)
        for i, f in enumerate(fig):
            f.savefig(f'{filename}_{i}.jpg')
    
    
    fig = make_fig(1)
    savefig('test1', fig)
    fig = make_fig(2)
    savefig('test2', fig)
    

    执行后,我们有test1_0.jpgtest2_0.jpgtest2_1.jpg

    作为if 检查的替代方法,您可以使用EAFP 方法:

    def savefig(filename, fig):
        try:
            fig.savefig(filename)
        except AttributeError:
            for i, f in enumerate(fig):
                f.savefig(f'{filename}_{i}.jpg')
    

    【讨论】:

    • 谢谢。在您的custom_savefig 中,我将如何引用fig
    • @SuperCiocia 和 self,我更新了我的答案
    • 但这仅在fig 是一个图形时才有效,因此它具有savefig 作为方法。如果我的fig = (fig1, fig2),其中fig1fig2 是数字怎么办?
    • @SuperCiocia 查看更新的答案,更简单、更安全的解决方案
    • @SuperCiocia from collections.abc import Iterable
    【解决方案2】:

    为此,您可以返回自己的对象,而不是返回元组,该对象将元组作为字段之一。

    class MultipleFigures:
    
        def __init__(self, figures):
            self.figures = figures
    
        def savefig(self):
            for fig in self.figures:
                fig.savefig()
    

    然后make fig 函数可以返回matplotlib.pytplot 实例或MultipleFigures 实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      相关资源
      最近更新 更多