Skip to content

Instantly share code, notes, and snippets.

@chikamichi
Created June 29, 2012 12:36
Show Gist options
  • Save chikamichi/3017677 to your computer and use it in GitHub Desktop.
Save chikamichi/3017677 to your computer and use it in GitHub Desktop.
d3: radial stack with nest
key axis value
min 1 2
avg 1 3.6
max 1 5
min 2 3
avg 2 8.2
max 2 10
min 3 0
avg 3 2.6
max 3 8
min 1 2
avg 1 3.6
max 1 5
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
background: #F2F2F2;
}
.layer.hover {
stroke: white;
}
</style>
<body>
<script src="http://d3js.org/d3.v2.min.js?2.9.5"></script>
<script>
var margin = {top: 10, right: 20, bottom: 20, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var angle = d3.scale.linear()
.range([0, 2 * Math.PI]);
var radius = d3.scale.linear()
.range([20, height / 2]);
var z = d3.scale.category20c();
var stack = d3.layout.stack()
.offset("zero")
.values(function(d) { return d.values; })
.x(function(d) { return d.axis; })
.y(function(d) { return d.value; });
var nest = d3.nest()
.key(function(d) { return d.key; });
var area = d3.svg.area.radial()
.interpolate('cardinal-closed')
.tension(1)
.angle(function(d,i) {
return angle(i);
})
.innerRadius(function(d) {
return radius(d.y0);
})
.outerRadius(function(d) {
return radius(d.y0 + d.y);
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.csv("data.csv", function(data) {
data.forEach(function(d) {
d.axis = +d.axis;
d.value = +d.value;
});
var layers = stack(nest.entries(data));
angle.domain([1, d3.max(data, function(d) { return d.axis }) + 1]);
radius.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]);
svg.selectAll(".layer")
.data(layers)
.enter().append("path")
.attr("class", function(d) {
return "layer " + d.key;
})
.attr("d", function(d) {
return area(d.values);
})
.style("fill", function(d, i) { return z(i); });
svg.selectAll('.layer')
.on('mouseover', function(d, i) {
d3.select(this).classed('hover', true);
})
.on('mouseout', function(d, i) {
d3.select(this).classed('hover', false);
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment