【问题标题】:How to show Vega visualizations in Google Colab如何在 Google Colab 中显示 Vega 可视化
【发布时间】:2020-08-31 05:07:06
【问题描述】:

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

我在 Google Colab 中尝试过 ipyvega。但是当我在 Google Colab 中运行他们的example 时,什么都没有出现,也没有错误。

【问题讨论】:

    标签: google-colaboratory vega altair


    【解决方案1】:

    启用 Colab 渲染器后,您可以使用 altair.vega.Vega 类在 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)
    

    【讨论】:

      【解决方案2】:

      你可以使用 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)
      

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 2020-08-04
        • 2023-01-14
        • 2022-01-14
        • 2020-10-10
        • 2021-11-23
        • 2020-06-04
        • 2021-01-07
        • 2020-07-21
        相关资源
        最近更新 更多