【发布时间】:2020-08-31 05:07:06
【问题描述】:
我可以使用 Altair 在 Google Colab 中显示 Vega-Lite 可视化。但是有没有办法显示简单的 Vega 可视化?
我在 Google Colab 中尝试过 ipyvega。但是当我在 Google Colab 中运行他们的example 时,什么都没有出现,也没有错误。
【问题讨论】:
标签: google-colaboratory vega altair
我可以使用 Altair 在 Google Colab 中显示 Vega-Lite 可视化。但是有没有办法显示简单的 Vega 可视化?
我在 Google Colab 中尝试过 ipyvega。但是当我在 Google Colab 中运行他们的example 时,什么都没有出现,也没有错误。
【问题讨论】:
标签: google-colaboratory vega altair
你可以使用 altair 的 vega 魔法。但它需要一些设置。
# 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)
【讨论】: