javascript-d3How do I create a donut chart using d3.js?
A donut chart can be created using d3.js by following these steps:
- Create an SVG element and set its width and height:
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
- 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 + ")");
- Create a color scale to use for the pie chart:
var color = d3.scaleOrdinal(d3.schemeCategory10);
- Create a pie layout and set its size and value accessor:
var pie = d3.pie()
.value(function(d) { return d.value; })
.sort(null);
- Create an arc generator and set its inner and outer radius:
var arc = d3.arc()
.innerRadius(radius - donutWidth)
.outerRadius(radius);
- 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); });
- 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
More of Javascript D3
- How do I use the z-index property with d3.js?
- How can I display Unix time using d3.js?
- How do I create a zoomable line chart using d3.js?
- How do I use d3.js to zoom to a selected area?
- How do I install and use D3.js with Yarn?
- How do I set up the x axis in d3.js?
- How do I create a zoomable chart using d3.js?
- How can I use d3.js to parse XML data?
- How do I create a flame graph using JS-D3 on Ubuntu?
- How do I use d3.js to implement zooming functionality?
See more codes...