Skip to content

Instantly share code, notes, and snippets.

@geohacker
Forked from mbostock/.block
Last active December 10, 2015 16:48
Show Gist options
  • Save geohacker/4463306 to your computer and use it in GitHub Desktop.
Save geohacker/4463306 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Bar Chart</title>
<script type="text/javascript" src="http://github.com/mbostock/d3/raw/v1.8.2/d3.js"></script>
<style type="text/css">
body {
font: 10px sans-serif;
}
</style>
</head>
<body>
<div class="value"></div>
<script type="text/javascript">
var n = 20, // number of samples
m = 4, // number of series
data = d3.range(m).map(function() { return d3.range(n).map(Math.random); });
var w = 940,
h = 460,
x = d3.scale.linear().domain([0, 1]).range([0, h]),
y0 = d3.scale.ordinal().domain(d3.range(n)).rangeBands([0, w], .2),
y1 = d3.scale.ordinal().domain(d3.range(m)).rangeBands([0, y0.rangeBand()]),
z = d3.scale.category10();
var vis = d3.select("body")
.append("svg:svg")
.attr("width", w + 20)
.attr("height", h + 40)
.append("svg:g")
.attr("transform", "translate(10,10)");
var g = vis.selectAll("g")
.data(data)
.enter().append("svg:g")
.attr("fill", function(d, i) { return z(i); })
.attr("transform", function(d, i) { return "translate(" + y1(i) + ",0)"; });
var rect = g.selectAll("rect")
.data(Object)
.enter().append("svg:rect")
.attr("transform", function(d, i) { return "translate(" + y0(i) + ",0)"; })
.attr("width", y1.rangeBand())
.attr("height", x)
.attr("y", function(d) { return h - x(d); });
vis.selectAll("rect").on("mouseover", mouseover);
var text = vis.selectAll("text")
.data(d3.range(n))
.enter().append("svg:text")
.attr("class", "group")
.attr("transform", function(d, i) { return "translate(" + y0(i) + ",0)"; })
.attr("x", y0.rangeBand() / 2)
.attr("y", h + 6)
.attr("dy", ".71em")
.attr("text-anchor", "middle")
.text(function(d, i) { return String.fromCharCode(65 + i); });
function mouseover(d) {
d3.select(".value").text(d);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment