How to implement d3.js donut chart?

Member

by samara , in category: Javascript , a month ago

How to implement d3.js donut chart?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a month ago

@samara 

To implement a d3.js donut chart, you can follow these steps:

  1. Include the d3.js library in your HTML file. You can use a CDN link to include the library:
1
<script src="https://d3js.org/d3.v7.min.js"></script>


  1. Create an SVG element in your HTML file where you want to display the donut chart:
1
<svg id="chart"></svg>


  1. Define the data that you want to display in the donut chart. This data should be in the form of an array of objects, where each object represents a category with a value:
1
2
3
4
5
var data = [
  {category: "Category 1", value: 30},
  {category: "Category 2", value: 50},
  {category: "Category 3", value: 20}
];


  1. Use d3.js to create the donut chart using the data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var width = 400;
var height = 400;
var radius = Math.min(width, height) / 2;

var color = d3.scaleOrdinal(d3.schemeCategory10);

var svg = d3.select("#chart")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var pie = d3.pie()
  .value(function(d) { return d.value; })
  .sort(null);

var arc = d3.arc()
  .innerRadius(radius - 100)
  .outerRadius(radius - 50);

var path = svg.selectAll("path")
  .data(pie(data))
  .enter()
  .append("path")
  .attr("d", arc)
  .attr("fill", function(d, i) {
    return color(i);
  });

var legend = svg.selectAll(".legend")
  .data(data)
  .enter()
  .append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) {
    return "translate(-50," + (i * 20 - 50) + ")";
  });

legend.append("rect")
  .attr("x", width - 18)
  .attr("width", 18)
  .attr("height", 18)
  .attr("fill", function(d, i) {
    return color(i);
  });

legend.append("text")
  .attr("x", width - 24)
  .attr("y", 9)
  .attr("dy", ".35em")
  .style("text-anchor", "end")
  .text(function(d) {
    return d.category;
  });


  1. Customize the appearance and styling of the donut chart as needed by modifying the code above.
  2. Finally, ensure to check the data and make sure it is formatted correctly, so it can be displayed correctly in the donut chart.