Skip to content

Instantly share code, notes, and snippets.

@versae
Last active December 25, 2015 13:49
Show Gist options
  • Save versae/6987098 to your computer and use it in GitHub Desktop.
Save versae/6987098 to your computer and use it in GitHub Desktop.
Showing a D3 bar chart inside IPython, taking advantage of the `new Function` alternative syntax in Javascript for creating functions
import json
class BarChart(object):
def __init__(self, val, values):
self.val = val
self.values = values
def _repr_html_(self):
def function(code, args=None):
script = "\\\n".join(code.split("\n"))
if not args:
return """new Function("{0}")""".format(script)
else:
return """new Function("{0}", "{1}")""".format(
'", "'.join(args),
script
)
datum_x = function(
args=["datum", "index"],
code="return x(index);"
)
datum_y = function(
args=["datum"],
code="return height - y(datum.books);"
)
datum_height = function(
args=["datum"],
code="return y(datum.books);"
)
datum_books = function(
args=["datum"],
code="return datum.books;"
)
load_chart = function(
args=["data"],
code="""
var barDemo = d3.select('#t{id}').
append('svg:svg').
attr('width', width).
attr('height', height);
barDemo.selectAll('rect').
data(data).
enter().
append('svg:rect').
attr('x', {datum_x}).
attr('y', {datum_y}).
attr('height', {datum_height}).
attr('width', barWidth).
attr('fill', '#2d578b');
"""
).format(
id=id(self.val),
datum_x=datum_x.replace('"', "'"),
datum_y=datum_y.replace('"', "'"),
datum_height=datum_height.replace('"', "'"),
)
render_chart = function(
code="""
x = d3.scale.linear().domain([0, data.length]).range([0, width]);
y = d3.scale.linear().domain([0, d3.max(data, {datum_books})]).rangeRound([0, height]);
return loadChart(data)"""
).format(datum_books=datum_books.replace('"', "'"))
script = """
<script>
var data = JSON.parse('{values}');
var barWidth = 40;
var width = (barWidth + 10) * data.length;
var height = 200;
var x, y;
var loadChart = {load_chart};
var renderChart = {render_chart};
if(typeof(d3) === 'undefined') {{
jQuery.getScript( 'http://d3js.org/d3.v3.min.js')
.done(renderChart);
}} else {{
loadChart(data);
}}
</script>
<marquee><em>{val}</em></marquee>
<div id="t{id}"></div>
""".format(
val=self.val,
values=json.dumps(self.values),
id=id(self.val),
datum_books=datum_books,
load_chart=load_chart,
render_chart=render_chart,
)
return script
BarChart("This may help you with your ouput! :-D", [
{"year": 2006, "books": 54},
{"year": 2007, "books": 43},
{"year": 2008, "books": 41},
{"year": 2009, "books": 44},
{"year": 2010, "books": 35}
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment