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

问题描述

我正在尝试实现一个自定义格式化程序 formatType,我可以在 jupyterlab 中将其与 altair 一起使用。我不知道如何在 jupyterlab 中注册 vega 表达式函数。它在使用 vega-editor 并使用 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,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 控制台定义的,例如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 中添加了 Vega-Lite 中的自定义格式化程序; Altair 当前支持 Vega-Lite v4.8.1,因此当前版本的 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,1e10]})
).mark_line(
).encode(
    y=alt.Y('y:Q'),x=alt.X('x:Q')
)