如何将 null 作为来自 python 的聚合字段的值传递?

问题描述

我想实现这一目标:

"$schema": "https://vega.github.io/schema/vega-lite/v4.json","mark": {"type": "bar","tooltip": true},"encoding": {

    "x": {"field": "Creative Type","type": "nominal","aggregate": null},"y": {"field": "Creative Type","aggregate": "count"}

我正在将值从 Python 传递给 vegalite。 由于 Python 没有 null 关键字,我不知道如何在 x 轴上将聚合的值设置为 null。任何帮助是极大的赞赏。谢谢!

解决方法

Python 中 null 关键字的等效项将是 None。请检查是否有效。

,

一般来说,在 Python/Altair 中传递 None 会在 JSON/vega 中产生 null。例如,当隐藏图例(Vega-Lite 中的 "legend": null)时,您可以在 Altair 中使用 legend=None,如Adjusting the Legend 中所述。

但是,在聚合的情况下,这不起作用:根据 Vega-Lite 架构,null 不是 aggregate 的有效参数,因此在 Altair 中尝试此操作将导致SchemaValidationError

如果由于某种原因你真的想生成这个无效的规范,你可以通过将 validate=False 传递给 alt.Chart.to_json 来实现:

import altair as alt
chart = alt.Chart().mark_bar(tooltip=True).encode(
    x=alt.X('Creative Type:N',aggregate=None),y=alt.Y('Creative Type:N',aggregate='count')
)
print(chart.to_json(validate=False))
# {
#   "$schema": "https://vega.github.io/schema/vega-lite/v4.8.1.json",#   "config": {
#     "view": {
#       "continuousHeight": 300,#       "continuousWidth": 400
#     }
#   },#   "encoding": {
#     "x": {
#       "aggregate": null,#       "field": "Creative Type",#       "type": "nominal"
#     },#     "y": {
#       "aggregate": "count",#       "type": "nominal"
#     }
#   },#   "mark": {
#     "tooltip": true,#     "type": "bar"
#   }
# }