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 PieChart = dc.pieChart("#piechart");
// 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 state
var dim = ndx.dimension(function(d) {return d.state});
//Here we group by state and sum on column population
var g = dim.group().reduceSum(function(d){return d.population;});
//Lets create a pie chart
PieChart.dimension(dim)
.radius(90)
.innerRadius(45) // used to create the donut effect
.group(g)
// These last two lines are not needed but are
// here to show you how to create custom titles
.title(function(d){ return d.data.key +": "+d.value;})
.renderTitle(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 + "")