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

2024-09-19 23:37:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现一个自定义格式化程序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控制台定义的,例如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似乎可以实现类似的行为,但是这不太通用,因为表达式必须在每个轴上重复。谢谢大家!


Tags: testimport程序return表达式jsfunctionalt
2条回答

一种可能的解决方法是使用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')
)

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

相关问题 更多 >