D3 Bar Chart with Update

This example is based on the canonical simple bar chart example, but with a minor twist - a data update is added to the chart in a Jupyter cell below the chart, which updates the chart with a transition.

Notebook Config


In [1]:
from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json, random

In [2]:
HTML('<script src="lib/d3/d3.min.js"></script>')


Out[2]:

Graph Config


In [3]:
html_template = Template('''
<style> $css_text </style>
<div id="graph-div"></div>
<script> $js_text </script>
''')

In [4]:
css_text = '''

.bar {
  fill: steelblue;
}

.bar:hover {
  fill: brown;
}

.axis {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}

'''

In [5]:
js_text_template = Template('''

var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 500 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var svg = d3.select("#graph-div").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var data = $data ;

  x.domain(data.map(function(d) { return d.letter; }));
  y.domain([0, d3.max(data, function(d) { return d.y; })]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.letter); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.y); })
      .attr("height", function(d) { return height - y(d.y); });

''')

In [6]:
js_text_template_2 = Template('''

var bars = svg.selectAll(".bar").data($data);
  
bars
  .transition()
    .attr("y", function(d) { return y(d.y); })
    .attr("height", function(d) { return height - y(d.y); });

''')

Initial Data, Graph and Update


In [7]:
data = pd.DataFrame({'letter': ['A','B','C','D'], 'y': [1,1,1,1]})
data.head()


Out[7]:
letter y
0 A 1
1 B 1
2 C 1
3 D 1

In [8]:
js_text = js_text_template.substitute({'data': json.dumps(data.to_dict(orient='records'))})
HTML(html_template.substitute({'css_text': css_text, 'js_text': js_text}))


Out[8]:

In [9]:
data['y'] = [random.uniform(0,1) for d in data['y']]
js_text = js_text_template_2.substitute({'data': json.dumps(data.to_dict(orient='records'))})
HTML('<script>' + js_text + '</script>')


Out[9]:

Re-run this last cell (ctrl-Enter lets you run it and stay put) and watch it transition the graph above it.