如何将默认值传递给 altair 编码

How to pass default value to altair encoding

我想根据条件改变 shape 参数,在某些情况下希望它保持默认值。但是,以下内容:

import altair as A
shape = A.Undefined
ch = A.Chart({}).encode(shape=shape)

加注TypeError: argument of type 'UndefinedType' is not iterable。这是一个错误,还是我可以传递适当的 'null' 值?

Altair 的 API 目前不支持任何标记来表示空编码。如果这对您的用例很重要,您可以在 https://github.com/altair-viz/altair/issues

打开功能请求

最好的解决方法是做这样的事情:

import altair as alt
shape = None

kwds = {} if shape is None else {'shape': shape}
ch = alt.Chart().encode(**kwds)

如果您正在寻找工具提示和大小的默认值,我使用了下面的示例。

import altair as alt
from vega_datasets import data

source = data.iris()
if size is None:
    size = {}
if tooltip is None:
    tooltip = []
alt.Chart(source).mark_circle().encode(
    alt.X('sepalLength', scale=alt.Scale(zero=False)),
    alt.Y('sepalWidth', scale=alt.Scale(zero=False, padding=1)),
    color='species',
    size=size,
    tooltip=tooltip
)