javascript - 如何在 iPython Notebook 中渲染 Dygraph?

标签 javascript python ipython jupyter-notebook dygraphs

我最终希望将数据从 python 数据结构传递到 Javascript 元素,这些元素将在 iPython Notebook 内的 Dygraphs 图中呈现它。

我对使用笔记本很陌生,尤其是 javascript/nobebook 交互。我在我的机器上本地保存了最新的 Dygraphs 库。至少,我希望能够使用该库在笔记本中渲染示例 Dygraphs 图。

请参阅下面的笔记本。我正在尝试使用此处提供的库执行简单的 Dygraphs 示例代码:http://dygraphs.com/1.0.1/dygraph-combined.js

但是,我似乎无法渲染任何内容。这是嵌入/调用库然后从笔记本中运行 javascript 的正确方法吗?

notebook

最终我想从 Pandas DataFrames 生成 JSON 并将该数据用作 Dygraphs 输入。

最佳答案

诀窍是将 DataFrame 传递到 JavaScript 中并将其转换为 format dygraphs 可以处理。这是我使用的代码( notebook here )

html = """
<script src="http://dygraphs.com/dygraph-combined.js"></script>
<div id="dygraph" style="width: 600px; height: 400px;"></div>

<script type="text/javascript">
function convertToDataTable(d) {
  var columns = _.keys(d);
  columns.splice(columns.indexOf("x"), 1);
  var out = [];
  for (var k in d['x']) {
    var row = [d['x'][k]];
    columns.forEach(function(col) {
      row.push(d[col][k]);
    });
    out.push(row);
  }
  return {data:out, labels:['x'].concat(columns)};
}

function handle_output(out) {
  var json = out.content.data['text/plain'];
  var data = JSON.parse(eval(json));
  var tabular = convertToDataTable(data);
  g = new Dygraph(document.getElementById("dygraph"), tabular.data, {
    legend: 'always',
    labels: tabular.labels
  })
}
var kernel = IPython.notebook.kernel;
var callbacks = { 'iopub' : {'output' : handle_output}};
kernel.execute("dfj", callbacks, {silent:false});
</script>
"""

HTML(html)

这就是它的样子:

chart rendered using dygraphs in an IPython notebook

该图表是完全交互式的:您可以悬停、平移、缩放以及以与典型的 dygraph 相同的方式进行交互。

关于javascript - 如何在 iPython Notebook 中渲染 Dygraph?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24687665/

相关文章:

python - 将 Glue Connection 资源的值传递给 Python Job

python - 需要列表的问题

python - 如何在任意超时后停止 Python 程序

python - 谷歌应用引擎、Python 和 IPython

ipython - 无法使 IPython 读取 shell 变量

使用分层索引将 Pandas 系列连接回源 DataFrame

javascript - 什么破坏了我的 Galaxy S3 上的 window.page?

javascript - 侧边栏的切换按钮

javascript - 获取ajax调用附带的隐藏字段值

Javascript 字符串转 Base64 UTF-16BE