2

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.

2 Answers 2

2

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.

4
  • This is perfect! It is faster and cleaner than my string building approach.
    – zachd1_618
    Commented Jul 15, 2014 at 16:30
  • Also, would you mind explaining the role of the kernel and how that plays into the notebook/javascript interaction?
    – zachd1_618
    Commented Jul 16, 2014 at 4:39
  • See this blog post for more info on kernel: jakevdp.github.io/blog/2013/06/01/…
    – danvk
    Commented Jul 17, 2014 at 6:23
  • I made a dygraphs wrapper for use in a notebook. Its got basic functionality for now, using what you provided as a template. github.com/DayStarEngineering/PyDyGraphs
    – zachd1_618
    Commented Aug 5, 2014 at 17:40
0

danvk's solution is cleaner and faster than this, but I also was able to get this to work by building a Dygraph String from a DataFrame. It seems limited to about 15K points, but the benefit is that once created, the page can be saved as a static html page and the Dygraphs plot stays in place. Makes for a nice portable sharing mechanism for those without notebooks set up.

CELL:

%%html
<script type="text/javascript" src="http://dygraphs.com/1.0.1/dygraph-combined.js"></script>`

CELL:

import string
import numpy as np
import pandas as pd
from IPython.display import display,Javascript,HTML,display_html,display_javascript,JSON
df = pd.DataFrame(columns=['x','y','z'])x=np.arange(1200)
df.y=np.sin(x*2*np.pi/10) + np.random.rand(len(x))*5
df.z=np.cos(x)
df.x=df.y+df.z/3 + (df.y-df.z)**1.25
s=df.to_csv(index_label="Index",float_format="%5f",index=True)
ss=string.join(['"' + x +'\\n"' for x in s.split('\n')],'+\n')
dygraph_str="""
<html>
<head>
<script type="text/javascript" src="http://dygraphs.com/1.0.1/dygraph-combined.js">    </script>
</head>
<body>
<div id="graphdiv5" style="margin: 0 auto; width:auto;"></div>
<script type="text/javascript">
  g = new Dygraph(
    document.getElementById("graphdiv5"),  // containing div
    """ + ss[:-6] + """,
    {
        legend: 'always',
        title: 'FOO vs. BAR',
        rollPeriod: 1,
        showRoller: true,
        errorBars: false,
        ylabel: 'Temperature (Stuff)'
    }
  );
</script>
"""
display(HTML(dygraph_str))

The notebook looks like this:enter image description here

1
  • The 15k limit you're running into is due to the trailing "+". When you have a deeply nested expression like N1+N2+N3+..., you eventually overflow the stack. The solution is to have a really long string on a single line, no concatenation necessary. Or, more concretely, where you have the string.join() line, change it to ss=json.dumps(s).
    – danvk
    Commented Jul 17, 2014 at 6:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.