Skip to content

Instantly share code, notes, and snippets.

@krish85
Last active August 29, 2015 14:27
Show Gist options
  • Save krish85/904a8e62140ee8aaada3 to your computer and use it in GitHub Desktop.
Save krish85/904a8e62140ee8aaada3 to your computer and use it in GitHub Desktop.
Donut Chart
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script>
var dataset = [
{ "task": "Work", "hours": 11},
{ "task": "Eat", "hours": 2},
{ "task": "Commute", "hours":2},
{ "task": "Watch TV", "hours": 2},
{ "task": "Sleep", "hours":7}
];
var width = 600;
var height = 500;
var radius = Math.min(width, height) / 3;
var color = d3.scale.category10();
var svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(180,180)');
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - 100);
var pie = d3.layout.pie()
.value(function(d) { return d.hours; })
.sort(null);
var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(i);
});
svg.selectAll("rect").data(dataset).enter().append("rect")
.attr("x",250)
.attr("y", function(d, i){ return (i * 30) - 50 })
.attr("height",20)
.attr("width",20)
.attr("fill",function(d, i) {
return color(i);
});
svg.selectAll("text").data(dataset).enter().append("text")
.attr("x",280)
.attr("y", function(d, i){ return (i * 30) - 35 })
.text(function(d){ return d.task;})
.attr("fill",function(d, i) {
return color(i);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment