9951 explained code solutions for 126 technologies


javascript-d3How do I create a donut chart using d3.js?


A donut chart can be created using d3.js by following these steps:

  1. Create an SVG element and set its width and height:
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);
  1. Create a group element and set its transform attribute to position the donut chart:
var g = svg.append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
  1. Create a color scale to use for the pie chart:
var color = d3.scaleOrdinal(d3.schemeCategory10);
  1. Create a pie layout and set its size and value accessor:
var pie = d3.pie()
    .value(function(d) { return d.value; })
    .sort(null);
  1. Create an arc generator and set its inner and outer radius:
var arc = d3.arc()
    .innerRadius(radius - donutWidth)
    .outerRadius(radius);
  1. Create a path element and set its d attribute to the arc generator:
g.selectAll(".arc")
    .data(pie(data))
    .enter().append("path")
    .attr("d", arc)
    .style("fill", function(d) { return color(d.data.label); });
  1. Add a label to the center of the donut chart:
var label = g.append("text")
    .attr("dy", ".35em")
    .style("text-anchor", "middle")
    .text(function(d) { return d.label; });

The output of this code will be a donut chart with a label in the center.

Helpful links

Edit this code on GitHub