首页 > 解决方案 > 使用 altair 在 jupyterlab 中注册自定义 vega 格式化程序

问题描述

我正在尝试实现一个可以在 jupyterlab 中与 altair 一起使用的自定义格式化程序formatType。我不知道如何在 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, 1e-2, 1, 1e10]})
).mark_line(
).encode(
    y=alt.Y('y:Q'),
    x=alt.X('x:Q', axis=alt.Axis(formatType='pubformat'))
)

在 Vega-lite 编辑器中打开定义按预期给出[Error] Unrecognized function: pubformat

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

在 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在轴上使用类似的行为,但是这不太通用,因为必须为每个轴重复表达式。谢谢!

标签: pythonjupyter-labaltairvega-litevega

解决方案


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


推荐阅读