Altair 构建在 Vega-Lite 之上,而不是直接构建在 Vega 之上。因此,Altair 中可用的变换是Vega-Lite 中指定的那些 https://vega.github.io/vega-lite/docs/transform.html。话虽如此,您可以直接在 Altair 中运行 Vega 规范,如下所示:
from altair.vega import Vega
Vega({
"$schema": "https://vega.github.io/schema/vega/v5.json",
"description": "An example of a circle packing layout for hierarchical data.",
"width": 600,
"height": 600,
"padding": 5,
"autosize": "none",
"data": [
{
"name": "tree",
"url": "https://raw.githubusercontent.com/vega/vega/main/docs/data/flare.json",
"transform": [
{
"type": "stratify",
"key": "id",
"parentKey": "parent"
},
{
"type": "pack",
"field": "size",
"sort": {"field": "value"},
"size": [{"signal": "width"}, {"signal": "height"}]
}
]
}
],
"scales": [
{
"name": "color",
"type": "ordinal",
"domain": {"data": "tree", "field": "depth"},
"range": {"scheme": "category20"}
}
],
"marks": [
{
"type": "symbol",
"from": {"data": "tree"},
"encode": {
"enter": {
"shape": {"value": "circle"},
"fill": {"scale": "color", "field": "depth"},
"tooltip": {"signal": "datum.name + (datum.size ? ', ' + datum.size + ' bytes' : '')"}
},
"update": {
"x": {"field": "x"},
"y": {"field": "y"},
"size": {"signal": "4 * datum.r * datum.r"},
"stroke": {"value": "white"},
"strokeWidth": {"value": 0.5}
},
"hover": {
"stroke": {"value": "red"},
"strokeWidth": {"value": 2}
}
}
}
]
})
请注意 Altair 中的 Vega 包装器可能会在未来版本中被弃用 https://github.com/altair-viz/altair/issues/2817因为现在可以使用 IPython 显示 Vega 和 Vega-Lite 规格:
import json
from IPython.display import display
vg_spec = r"""{
"$schema": "https://vega.github.io/schema/vega/v5.json",
"description": "An example of a circle packing layout for hierarchical data.",
"width": 600,
"height": 600,
"padding": 5,
"autosize": "none",
"data": [
{
"name": "tree",
"url": "https://raw.githubusercontent.com/vega/vega/main/docs/data/flare.json",
"transform": [
{
"type": "stratify",
"key": "id",
"parentKey": "parent"
},
{
"type": "pack",
"field": "size",
"sort": {"field": "value"},
"size": [{"signal": "width"}, {"signal": "height"}]
}
]
}
],
"scales": [
{
"name": "color",
"type": "ordinal",
"domain": {"data": "tree", "field": "depth"},
"range": {"scheme": "category20"}
}
],
"marks": [
{
"type": "symbol",
"from": {"data": "tree"},
"encode": {
"enter": {
"shape": {"value": "circle"},
"fill": {"scale": "color", "field": "depth"},
"tooltip": {"signal": "datum.name + (datum.size ? ', ' + datum.size + ' bytes' : '')"}
},
"update": {
"x": {"field": "x"},
"y": {"field": "y"},
"size": {"signal": "4 * datum.r * datum.r"},
"stroke": {"value": "white"},
"strokeWidth": {"value": 0.5}
},
"hover": {
"stroke": {"value": "red"},
"strokeWidth": {"value": 2}
}
}
}
]
}
"""
display({"application/vnd.vega.v5+json": json.loads(vg_spec)}, raw=True)