Cuttlepress

Blogging about Hacker School?

Day 40

I started the day without a lot of direction, and Julia suggested that I take the day to learn D3. Good idea! I worked through this tutorial and generated this exponentially-scaled bar chart of all my monetary transactions (not including rent/utilities) while I’ve been in NY: Color-coded!

Here’s the entirety of the JavaScript (colors were styled in the CSS):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var width = document.documentElement.clientWidth-10;
var height = 500;
var svg =  d3.select("body").append("svg").attr("width",width).attr("height",height);

d3.csv("new_york_money.csv", function(error, rows) {
  makeChart(rows);
});



function makeChart(dataset) {
  var yScale = d3.scale.pow()
      .domain([0, d3.max(dataset, function(d) { return +d.Amount; })])
      .range([0, height])
      .exponent(0.4);

  svg.selectAll("rect")
      .data(dataset)
      .enter()
      .append("rect")
      .attr("x", function(d, i) {
          return (i-1)*(width/(dataset.length));
      })
      .attr("width", function(d, i) {
          return width/dataset.length - dataset.length/100;
      })
      .attr("y", function(d) { return height-yScale(+d.Amount); })
      .attr("height", function(d) { return height;})
      .attr("class", function(d) { return d.Category; });
}