Skip to content

Instantly share code, notes, and snippets.

@santiagogaray
Last active March 7, 2018 21:35
Show Gist options
  • Save santiagogaray/e203193d9a8ba21be9a25b797880ac71 to your computer and use it in GitHub Desktop.
Save santiagogaray/e203193d9a8ba21be9a25b797880ac71 to your computer and use it in GitHub Desktop.
histogram
license: mit
name age
Mark 5
Mark 1
Mark 35
Mark 55
Mark 6
Mark 3
Mark 34
Mark 76
Mark 23
Mark 64
Mark 23
Mark 1
Mark 3
Mark 6
Mark 14
Mark 13
Mark 11
Mark 25
Mark 35
Mark 45
Mark 55
Mark 25
Mark 34
Mark 54
Mark 53
Mark 52
Mark 51
Mark 45
Mark 47
Mark 36
Mark 39
Mark 8
Mark 19
Mark 56
Mark 87
Mark 76
Mark 74
Mark 73
Mark 26
Mark 45
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar rect {
fill: steelblue;
}
.bar text {
fill: #fff;
font: 10px sans-serif;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
d3.csv("histogram.csv", function (data) {
map = data.map(function(d,i){ return parseFloat(d.age); })
var formatCount = d3.format(",.0f");
var svg = d3.select("svg"),
margin = {top: 10, right: 30, bottom: 30, left: 30},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.rangeRound([0, width])
.domain([0,d3.max(map)]);
var bins = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(10))
(map);
var y = d3.scaleLinear()
.domain([0, d3.max(bins, function(d) { return d.length; })])
.range([height, 0]);
var bar = g.selectAll(".bar")
.data(bins)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });
bar.append("rect")
.attr("x", 1)
.attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
.attr("height", function(d) { return height - y(d.length); });
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.length); });
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment