How to draw multiseries donut chart using d3.js?

by mallory_cormier , in category: Javascript , 4 months ago

How to draw multiseries donut chart using d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 4 months ago

@mallory_cormier 

To draw a multi-series donut chart using d3.js, you can follow these steps:

  1. Include the d3.js library in your HTML file:
1
<script src="https://d3js.org/d3.v7.min.js"></script>


  1. Create a container element in your HTML where the chart will be rendered:
1
<div id="chart"></div>


  1. Define the data for your chart. The data should be in an array of objects, where each object represents a series. Each object should have two properties: label and data. The label property represents the name of the series, and the data property represents the value of the series.
1
2
3
4
5
var data = [
  { label: "Series 1", data: 30 },
  { label: "Series 2", data: 20 },
  { label: "Series 3", data: 50 }
];


  1. Calculate the total value of all the series to determine the angles of the donut chart:
1
var total = d3.sum(data, function(d) { return d.data; });


  1. Define the dimensions of the SVG element and the radius of the donut chart:
1
2
3
var width = 400;
var height = 400;
var radius = Math.min(width, height) / 2;


  1. Create the SVG element and append it to the container element:
1
2
3
4
5
6
var svg = d3.select("#chart")
  .append("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");


  1. Define a D3 arc generator to create the donut segments:
1
2
3
var arc = d3.arc()
  .innerRadius(radius * 0.6)
  .outerRadius(radius);


  1. Create a D3 pie layout to convert the data into start and end angles for the donut segments:
1
2
3
var pie = d3.pie()
  .value(function(d) { return d.data; })
  .sort(null);


  1. Bind the data to SVG path elements and draw the donut segments:
1
2
3
4
5
6
var path = svg.selectAll("path")
  .data(pie(data))
  .enter()
  .append("path")
  .attr("d", arc)
  .attr("fill", function(d, i) { return d3.schemeCategory10[i]; });


  1. Add text labels inside the donut segments:
1
2
3
4
5
6
7
var text = svg.selectAll("text")
  .data(pie(data))
  .enter()
  .append("text")
  .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
  .attr("text-anchor", "middle")
  .text(function(d) { return d.data; });


That's it! You have successfully created a multi-series donut chart using d3.js. Customize the styles and add any additional elements as needed.