首页 > 解决方案 > figure.show() 不显示

问题描述

我维护了一个实现该功能的精美绘图包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()

这是故意的吗?

如果是的话,我当然可以向用户询问 import matplotlib 并称plt.show()自己为 - 这行得通。我宁愿避免暴露这些信息并强迫用户导入一些东西只是为了显示这个数字。是否有其他一些我可以返回的对象show()savefig()等等?

标签: pythonmatplotlib

解决方案


您可以向 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()

推荐阅读