import pandas as pd
import jinja2
from IPython.display import display, Javascript, HTML
def inline_dc(stuff):
"""
Embeds the HTML source of the dc charts directly into the IPython notebook.
This method will not work if the dc charts depends on any files (json data). Also this uses
the HTML5 srcdoc attribute, which may not be supported in all browsers.
"""
return HTML(''.format(srcdoc=stuff.replace('"', '"')))
head = HTML("""
""")
df = pd.DataFrame({'population':[234,345,345,34],
'age':[2,3,6,9],
'state':['a','b','c','d'],
'state2':['d','c','b','a']})
df
dc = jinja2.Template(
"""
// Create Global Variables
var LineChart = dc.lineChart("#linechart");
// Load data
var dataset = {{ data }};
// Call function
Graph(dataset);
// Create function
function Graph(data) {
// Feed it through crossfilter
var ndx = crossfilter(data);
// for testing
//console.log(data);
//define a dimension
//Here we will group by population
var dim = ndx.dimension(function(d) {return d.population});
//Here we group by population and sum on column population
var g = dim.group().reduceSum(function(d){return d.population;});
//Lets create a line chart
LineChart.dimension(dim)
.group(g)
.width(800)
.height(200)
.elasticY(true) // rescale axis to fit data
.x(d3.scale.linear().domain([0,g.top(1)[0].value]))
.brushOn(false)
.dotRadius(10) // radius after hoover over datapoint
.renderHorizontalGridLines(true);
dc.renderAll(); // render all charts on the page
}; // end graph function
""")
body_js = Javascript(dc.render(
data=df.to_json(orient='records')
))
inline_dc(head.data + body_html.data + "")