使用 altair 在 jupyterlab 中注册自定义 vega 格式化程序

Registering custom vega formatters in jupyterlab with altair

我正在尝试实现一个自定义格式化程序 formatType,我可以在 jupyterlab 中与 altair 一起使用。我不知道如何在 jupyterlab 中注册 vega 表达式函数。它在使用 vega 编辑器并使用 JS 控制台注入表达式时有效。如何从 jupyterlab 单元格注册表达式函数?

使用

生成的定义
import altair as alt
import pandas as pd

def pub_theme():
    return {'config': {"customFormatTypes": True}}
alt.themes.register('pub', pub_theme)
alt.themes.enable('pub')

alt.Chart(
    pd.DataFrame({'x': [1e-3, 1e-2, 1, 1e10], 'y':[1e-3, 1e-2, 1, 1e10]})
).mark_line(
).encode(
    y=alt.Y('y:Q'),
    x=alt.X('x:Q', axis=alt.Axis(formatType='pubformat'))
)

opening the definition in the Vega-lite editor 按预期给出 [Error] Unrecognized function: pubformat

如果 pubformat 是通过 JS 控制台 witg 定义的,例如VEGA_DEBUG.vega.expressionFunction('pubformat', function() {return 'test'}),然后编辑器在 x 轴上生成具有 6 个相同标签 test 的预期输出。

在 jupyterlab 中实现此目标的正确方法是什么?

从 jupyterlab 页面上的 JS 控制台注入表达式 vega.expressionFunction('pubformat', function() {return 'test'}) 无效。通过

定义它
from IPython.display import HTML
    HTML("""
        <script>
            vega.expressionFunction('pubformat', function() {return 'test'})
        </script>
     """)

也没用。

如果注入 javascript 是一个问题,是否有任何其他选项可以在 altair 中实现自定义格式化程序?似乎在轴上使用 labelExpr 可以实现类似的行为,但这不太通用,因为必须为每个轴重复表达式。谢谢!

version 4.11; Altair currently supports Vega-Lite v4.8.1 中添加了 Vega-Lite 中的自定义格式化程序,因此当前版本的 Altair 不支持自定义格式化程序。

一种可能的解决方法是使用 labelExpr 。我可以使用

实现所需的行为
import altair as alt
import pandas as pd

def pub_theme():
    return {'config': {"axis": {"labelExpr": "replace(datum.label, datum.label, 'test')"}}}
alt.themes.register('pub', pub_theme)
alt.themes.enable('pub')

alt.Chart(
    pd.DataFrame({'x': [1e-3, 1e-2, 1, 1e10], 'y':[1e-3, 1e-2, 1, 1e10]})
).mark_line(
).encode(
    y=alt.Y('y:Q'),
    x=alt.X('x:Q')
)