如何在 Google Colab 中显示 Vega 可视化

How to show Vega visualizations in Google Colab

我可以使用 Altair 在 Google Colab 中显示 Vega-Lite 可视化。但是有没有办法显示普通的 Vega 可视化效果?

我在 Google Colab 中尝试了 ipyvega in Google Colab. But when I run their example,然后没有任何显示,也没有错误。

启用 Colab 渲染器后,您可以使用 altair.vega.Vega class 在 Colab 中显示 vega 图表。

这是一个例子:

from urllib import request
import json
with request.urlopen("https://vega.github.io/vega/examples/bar-chart.vg.json") as f:
  spec = json.load(f)

from altair import vega
vega.renderers.enable('colab')
vega.Vega(spec)

您可以使用 altair 的织女星魔法。但它需要一些设置。

# setup
!pip -q install -U PyYAML
from altair.vega import Vega
Vega.renderers.enable('colab')
%load_ext altair

然后使用 %%vega 魔法。

%%vega
{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "width": 400,
  "height": 200,
  "data": [
    {
      "name": "table",
      "values": [
        {"category": "A", "amount": 28},
        {"category": "B", "amount": 55},
        {"category": "C", "amount": 43},
        {"category": "D", "amount": 91},
      ]
    }
  ],

  "scales": [
    {
      "name": "xscale",
      "type": "band",
      "domain": {"data": "table", "field": "category"},
      "range": "width",
    },
    {
      "name": "yscale",
      "domain": {"data": "table", "field": "amount"},
      "range": "height"
    }
  ],

  "axes": [
    { "orient": "bottom", "scale": "xscale" },
    { "orient": "left"  , "scale": "yscale" }
  ],

  "marks": [
    {
      "type": "rect",
      "from": {"data":"table"},
      "encode": {
        "enter": {
          "x": {"scale": "xscale", "field": "category"},
          "width": {"scale": "xscale", "band": 1},
          "y": {"scale": "yscale", "field": "amount"},
          "y2": {"scale": "yscale", "value": 0}
        },
      }
    }
  ]
}

然后显示简单的条形图。

如果 vega 规范已经在字典中,使用 Vega(spec) 会更容易。

from requests import get
url = 'https://vega.github.io/vega/examples/bar-chart.vg.json'
spec = get(url).json()
Vega(spec)