我维护了一个奇特的绘图包,它实现了函数plot_foobar()。它返回带有绘图的图形,以便用户可以对其执行某些操作,例如,将其保存到文件(savefig())或显示。不幸的是,show()什么也不做。
MWE:
def plot_foobar():
# fancy plotting routing in a package
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1, 2], [3, 4])
return fig
# the user invokes the plotting function and gets back the figure object
fig = plot_foobar()
# saving the file works
# fig.savefig("out.png")
# :(
fig.show()
# works, but is clumsy:
# import matplotlib.pyplot as plt
# plt.show()这是故意的吗?
如果是,我当然可以要求用户导入matplotlib并调用plt.show() --这样就行了。我宁愿避免暴露这些信息,并强迫用户只为了显示图形而导入一些东西。有没有其他我可以返回的对象,可以在show(),savefig()等上工作?
发布于 2021-08-11 18:19:19
这里的一个基本问题是matplotlib "show loop“是一个全局对象。有一些努力试图让fig.show()真正做一些事情,但它并不是指日可待。现在,可以返回全局plt对象
def plot_foobar():
# fancy plotting routing in a package
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1, 2], [3, 4])
return plt对于用户来说,它与fig没有什么不同,因为用户可以对当前图形执行plt.show()或任何其他操作。
发布于 2021-07-02 03:27:55
您可以向Figure实例添加一个装饰器,以在其中调用plt.show():
def show_figure(f):
'''
Decorator to change fig.show() behavior.
'''
def wrapper():
import matplotlib.pyplot as plt
f() # call the original fig.show(), remove this line if there is no need to run fig.show()
plt.show()
return wrapper
def plot_foobar():
# fancy plotting routing in a package
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1, 2], [3, 4])
fig.show = show_figure(fig.show) # assign a decorator
return fig
# the user invokes the plotting function and gets back the figure object
fig = plot_foobar()
fig.show()https://stackoverflow.com/questions/68215473
复制相似问题