问题
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