是什么导致了Altair图表在JupyterLab单元格中的最后一条语句时显示?

时间:2020-08-28 19:47:52

标签: python jupyter-lab altair

我有一个要在JupyterLab中使用的类。当JupyterLab笔记本中的最后一条语句求值为我的类的实例时,我想显示一个表示我的类对象的Altair Chart。推荐的方法是什么?在下面的示例中,在这种情况下,似乎在类上调用了repr函数,因此这是一个钩子,我可以用它来控制JupyterLab笔记本中的最后一条语句求值为的一个实例时发生的情况我的课。但是,我不确定下一步该怎么做。我可以在代表我的对象的Altair display上调用Chart,然后返回一个空字符串。但是,返回一个空字符串而不是更有意义的东西似乎有点奇怪。例如,如果我想在其他上下文中使用repr来显示对象的表示形式,那么我将无法使用。当我在Altair repr上调用Chart时,我得到了类似alt.Chart(...)的字符串,因此似乎必须有其他方法来控制JupyterLab单元格中的最后一条语句时发生的情况是一些对象。有更好的方法吗?

import altair as alt
import numpy as np
import pandas as pd

class RandomWalk:
    def __init__(self, n):
        self._data = pd.DataFrame({
            'x': np.arange(n) + 1,
            'y': np.cumsum(np.random.normal(size=n)),
        })
        self._chart = alt.Chart(self._data).mark_line().encode(x='x', y='y')
    
    def __repr__(self):
        # When I use the following line for the body of __repr__, then
        # JupyterLab prints the string 'alt.Chart(...)' and does not display
        # the chart.
        # return repr(self._chart)
        # The following line displays the chart as desired, but it feels odd to
        # then also return the empty string.
        self._chart.display()
        return ''

RandomWalk(100)

1 个答案:

答案 0 :(得分:1)

Altair图表通过Jupyter的_repr_mimebundle_方法显示。您可以在此处查看Altair的定义:https://github.com/altair-viz/altair/blob/v4.1.0/altair/vegalite/v4/api.py#L1644-L1654

您可以在IPython文档Integrating your objects with IPython中了解更多有关此内容的信息。

创建RandomWalk类的最简单方法如下所示:

class RandomWalk:
    def __init__(self, n):
        self._data = pd.DataFrame({
            'x': np.arange(n) + 1,
            'y': np.cumsum(np.random.normal(size=n)),
        })
        self._chart = alt.Chart(self._data).mark_line().encode(x='x', y='y')

    def _repr_mimebundle_(self, include=None, exclude=None):
        return self._chart._repr_mimebundle_(include, exclude)