使用 __repr__ 等返回 matplotlib fig

Returning matplotlib fig with __repr__ or the like

我正在构建一个 Python class 用于构建 matplotlib 图表。我选择使用 class 是因为我希望能够通过一系列步骤构建图表,而不是使用一个接受大量参数的函数。

我的主要工作环境是 Jupyter Lab,我通常关闭交互式绘图,即 plt.ioff()。相反,我喜欢使用 display() 或通过将图形放在单元格的最后一行来隐式显示图形。

class Example:

    def __init__(self):

        self.fig, self.ax = plt.subplots()

使用上面的例子,我知道我可以做这样的事情

display(Example().fig)

但是,我希望有一种方法可以使 .fig 隐式化,这样我就可以做到 display(Example())。我原本以为我可以做到

def __repr__():
    return self.fig

但这种方法似乎行不通。有办法吗?

也许你可以使用 eval。这是打印 'subplots' 和 returns 字符串值为零的内容。

class Example:
    def __init__(self):
        pass

    def __repr__(self):
        eval(self.__to_eval())
        return '0'

    def __to_eval(self):
        return "print('subplots')"

示例:

In [0]: Example()
subplots
Out[20]: 0

我想你想显示图形的 png 表示,所以

class Example:

    def __init__(self):
        self.fig, self.ax = plt.subplots()

    def _repr_png_(self):
        return display(self.fig)