如何将Vega嵌入jupyterlab或笔记本中?

时间:2019-07-21 19:46:04

标签: jupyter vega

我正在尝试从vega复制粘贴示例,但收到“未定义vega”错误。

%%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有什么特别之处?

2 个答案:

答案 0 :(得分:1)

“头”声明在Jupyter cel中不起作用。您可以尝试使用类似方法来定义vegaEmbed:

int length = strlen(tmp);

然后,仅包含正文HTML的cel应该起作用。 (注意:请在普通的Jupyter笔记本中尝试此操作,而不是在Jupyterlab中尝试。)

更新

这在jupyter笔记本中有效,但在JupyterLab中不起作用:

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

答案 1 :(得分:1)

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

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

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