|
<!DOCTYPE html> |
|
<meta charset="utf-8"> |
|
<style> |
|
|
|
body { |
|
font: 10px sans-serif; |
|
} |
|
|
|
.axis path, |
|
.axis line { |
|
fill: none; |
|
stroke: #000; |
|
shape-rendering: crispEdges; |
|
} |
|
|
|
.bar { |
|
fill: steelblue; |
|
} |
|
|
|
.x.axis path { |
|
display: none; |
|
} |
|
|
|
</style> |
|
<body> |
|
<script src="//d3js.org/d3.v3.min.js"></script> |
|
<script> |
|
// Update to accept width and height |
|
// put redraw into a method |
|
|
|
|
|
class BarChart { |
|
|
|
constructor(filename, width, height) { |
|
this.width = width; |
|
this.height = height; |
|
this.filename = filename; |
|
this.setup(); |
|
} |
|
|
|
start() { |
|
this.grabData(this.filename, this.update.bind(this)) |
|
} |
|
|
|
grabData(filename, cb) { |
|
d3.tsv(filename, type, cb) |
|
} |
|
|
|
setup() { |
|
var margin = {top: 20, right: 30, bottom: 30, left: 40}; |
|
this.width = this.width - margin.left - margin.right, |
|
this.height = this.height - margin.top - margin.bottom; |
|
|
|
this.x = d3.scale.ordinal() |
|
.rangeRoundBands([0, this.width], 0.1, 0.2); |
|
|
|
this.y = d3.scale.linear() |
|
.range([this.height, 0]); |
|
|
|
this.svg = d3.select("body").append("svg") |
|
.attr("width", this.width + margin.left + margin.right) |
|
.attr("height", this.height + margin.top + margin.bottom) |
|
.append("g") |
|
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); |
|
} |
|
|
|
update(error, letters) { |
|
console.log(error); |
|
|
|
// need to pull these out for d3 overwrites `this` in all of its callbacks |
|
var x = this.x; |
|
var y = this.y; |
|
var height = this.height; |
|
|
|
x.domain(letters.map(function (d) { |
|
return d.letter; |
|
})); |
|
y.domain([0, d3.max(letters, function (d) { |
|
return d.frequency; |
|
})]); |
|
|
|
this.svg.append("g") |
|
.attr("class", "x axis") |
|
.attr("transform", "translate(0," + this.height + ")") |
|
.call(d3.svg.axis().scale(x).orient("bottom")); |
|
|
|
this.svg.append("g") |
|
.attr("class", "y axis") |
|
.call(d3.svg.axis().scale(y).orient("left")); |
|
|
|
this.svg.selectAll(".bar") |
|
.data(letters) |
|
.enter().append("rect") |
|
.attr("class", "bar") |
|
.attr("x", function (d) { |
|
return x(d.letter); |
|
}) |
|
.attr("width", this.x.rangeBand()) |
|
.attr("y", function (d) { |
|
return y(d.frequency); |
|
}) |
|
.attr("height", function (d) { |
|
return height - y(d.frequency); |
|
}); |
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
function type(d) { |
|
d.frequency = +d.frequency; |
|
return d; |
|
} |
|
|
|
|
|
|
|
var chart = new BarChart("letter-frequency.tsv", 960, 500); |
|
chart.start(); |
|
|
|
</script> |