How to show Vega visualizations in Google Colab

扶醉桌前 提交于 2021-02-10 05:33:08

问题


I can use Altair to show Vega-Lite visualizations in Google Colab. But is there a way to show plain Vega visualizations?

I tried ipyvega in Google Colab. But when I run their example in Google Colab, then nothing shows up, and there is no error.


回答1:


You can display a vega chart in Colab using the altair.vega.Vega class, once you have enabled the Colab renderer.

Here is an example:

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)




回答2:


You can use vega magic from altair. But it needs some setup.

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

Then use the %%vega magic.

%%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}
        },
      }
    }
  ]
}

The simple bar chart is then displayed.

If the vega spec is already in a dict, using Vega(spec) is easier.

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


来源:https://stackoverflow.com/questions/61801180/how-to-show-vega-visualizations-in-google-colab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!