Skip to content

Instantly share code, notes, and snippets.

@d3byex
Last active December 14, 2015 00:57
Show Gist options
  • Save d3byex/ef8f4fcdbd92a4226fea to your computer and use it in GitHub Desktop.
Save d3byex/ef8f4fcdbd92a4226fea to your computer and use it in GitHub Desktop.
D3byEX 10.7: Chord Diagram
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="D3byEX 10.7" />
<meta charset="utf-8">
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960, height = 500;
var svg = d3.select('body')
.append('svg')
.attr({
width: width,
height: height
});
var mainGroup = svg.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
var matrix = [
[11975, 5871, 8916, 2868],
[1951, 10048, 2060, 6171],
[8010, 16145, 8090, 8045],
[1013, 990, 940, 6907]
];
var layout = d3.layout.chord()
.padding(.05)
.matrix(matrix);
var fill = d3.scale.ordinal()
.domain(d3.range(4))
.range(['#000000', '#FFEE89', '#957244', '#FF0023']);
var innerRadius = Math.min(width, height) * .41,
outerRadius = innerRadius * 1.1;
mainGroup.append('g')
.selectAll('path')
.data(layout.groups)
.enter().append('path')
.style('fill', function(d) { return fill(d.index); })
.style('stroke', function(d) { return fill(d.index); })
.attr('d', d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius));
mainGroup.append('g')
.selectAll('path')
.data(layout.chords)
.enter()
.append('path')
.attr('d', d3.svg.chord()
.radius(innerRadius))
.style('fill', function(d) { return fill(d.target.index); })
.style({
opacity: 1,
'fill-opacity': 0.67,
stroke: '#000',
'stroke-width': '0.5px'
});
var ticks = mainGroup.append('g')
.selectAll('g')
.data(layout.groups)
.enter()
.append('g')
.selectAll('g')
.data(groupTicks)
.enter()
.append('g')
.attr('transform', function (d) {
return 'rotate(' + (d.angle * 180 / Math.PI - 90) + ')'
+ 'translate(' + outerRadius + ',0)';
});
ticks.append('line')
.attr({
x1: 1, y1: 0,
x2: 5, y2: 0,
stroke: 'black'
});
ticks.append('text')
.attr({
'x': 8,
'dy': '.35em',
'transform': function (d) { return d.angle > Math.PI ? 'rotate(180)translate(-16)' : null; }
})
.style('text-anchor', function (d) { return d.angle > Math.PI ? 'end' : null; })
.style('font', '10px sans-serif')
.text(function (d) { return d.label; });
// Returns an array of tick angles and labels, given a group.
function groupTicks(d) {
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, 1000).map(function (v, i) {
return {
angle: v * k + d.startAngle,
label: i % 5 ? null : v / 1000 + 'k'
};
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment