【发布时间】: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 循环。
如果a 是matplotlib.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')
【问题讨论】: