Search code examples
javascriptpythonipythonjupyter-notebookdygraphs

How to Render Dygraph in iPython Notebook?


I would eventually like to pass data from python data structures to Javascript elements that will render it in a Dygraphs graph within an iPython Notebook.

I am new to using notebooks, especially the javascript/nobebook interaction. I have the latest Dygraphs library saved locally on my machine. At the very least, I would like to be able to render a sample Dygraphs plot in the notebook using that library.

See the notebook below. I am trying to execute the simple Dygraphs example code, using the library provided here: http://dygraphs.com/1.0.1/dygraph-combined.js

However, I cannot seem to get anything to render. Is this the proper way to embed/call libraries and then run javascript from within a notebook?

notebook

Eventually I would like to generate JSON from Pandas DataFrames and use that data as Dygraphs input.


Solution

  • The trick is to pass the DataFrame into JavaScript and convert it into a format that dygraphs can handle. Here's the code I used (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)
    

    This is what it looks like:

    chart rendered using dygraphs in an IPython notebook

    The chart is fully interactive: you can hover, pan, zoom and otherwise interact in the same ways that you would with a typical dygraph.