如何在 jupyterlab 或 notebook 中嵌入 vega?

How to embed vega in jupyterlab or notebook?

我正在尝试从 vega 复制粘贴示例,但出现 "vega is not defined" 错误。

%%html
<!DOCTYPE html>
<html>
<head>
  <!-- Import Vega 5 & Vega-Lite 3 (does not have to be from CDN) -->
  <script src="https://cdn.jsdelivr.net/npm/vega@[5]"></script>
  <script src="https://cdn.jsdelivr.net/npm/vega-lite@[5]"></script>
  <!-- Import vega-embed -->
  <script src="https://cdn.jsdelivr.net/npm/vega-embed@[5]"></script>
</head>
<body>

<div id="vis"></div>

<script type="text/javascript">
  var spec = "https://raw.githubusercontent.com/vega/vega/master/docs/examples/bar-chart.vg.json";
  vegaEmbed('#vis', spec).then(function(result) {
    // Access the Vega view instance (https://vega.github.io/vega/docs/api/view/) as result.view
  }).catch(console.error);
</script>
</body>
</html>

jupyterlab 如何处理 html/js 打破这一点的魔法有什么特别之处吗?

"head" 声明在 Jupyter cel 中不起作用。你可以尝试这样来定义 vegaEmbed:

<script>
requirejs.config({
  baseUrl: 'https://cdn.jsdelivr.net/npm/',
  paths: {
    "vega-embed":  "vega-embed@5?noext",
    "vega-lib": "vega-lib?@5noext",
    "vega-lite": "vega-lite@4?noext",
    "vega": "vega@5?noext"
  }
});

requirejs(["vega", "vega-embed"], function(vega, vegaEmbed) {
     console.log(vega.version);
     console.log(vegaEmbed.version);
     window.vegaEmbed=vegaEmbed;
     window.vega = vega;});
</script>

然后只有主体 HTML 的 cel 应该可以工作。 (注意:在普通的 Jupyter notebook 中尝试过,而不是 Jupyterlab。)

更新:

这适用于 jupyter 笔记本,但不适用于 JupyterLab:

%%html
<script>
requirejs.config({
  baseUrl: 'https://cdn.jsdelivr.net/npm/',
  paths: {
    "vega-embed":  "vega-embed@5?noext",
    "vega-lib": "vega-lib?@5noext",
    "vega-lite": "vega-lite@4?noext",
    "vega": "vega@5?noext"
  }
});

requirejs(["vega", "vega-embed"], function(vega, vegaEmbed) {
     console.log(vega.version);
     console.log(vegaEmbed.version);
     window.vegaEmbed=vegaEmbed;
     window.vega = vega;});
</script>

<body>

<div id="vis"></div>

<script type="text/javascript">
  var spec = "https://raw.githubusercontent.com/vega/vega/master/docs/examples/bar-chart.vg.json";
  vegaEmbed('#vis', spec).then(function(result) {
    // Access the Vega view instance (https://vega.github.io/vega/docs/api/view/) as result.view
  }).catch(console.error);
</script>
</body>

如果你不介意安装 altair,你可以这样做:

from altair.vega import vega
import json
with open("bar-chart.vg.json") as f:
    s = json.load(f)
vega(s)

这在 Jupyter Lab 中绝对有效,笔记本不确定