How to change color of donut chart created using d3.js?

Member

by darion , in category: Javascript , 8 months ago

How to change color of donut chart created using d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 8 months ago

@darion 

To change the color of a donut chart created using d3.js, you can use the fill attribute in the path elements of the chart. Here is an example code snippet showing how to change the color of the chart:

 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
// Create a color scale
var color = d3.scaleOrdinal()
    .range(["#ffcc66", "#ff9966", "#ff6666", "#cc6666", "#996666"]);

// Create the donut chart
var pie = d3.pie()
    .value(function(d) { return d.value; });
    
var arc = d3.arc()
    .innerRadius(50)
    .outerRadius(100);

var data = [{
    label: "A",
    value: 20
}, {
    label: "B",
    value: 30
}, {
    label: "C",
    value: 40
}, {
    label: "D",
    value: 10
}, {
    label: "E",
    value: 50
}];

var svg = d3.select("body")
    .append("svg")
    .attr("width", 200)
    .attr("height", 200)
    .append("g")
    .attr("transform", "translate(100, 100)");
    
var path = svg.selectAll("path")
    .data(pie(data))
    .enter()
    .append("path")
    .attr("d", arc)
    .attr("fill", function(d, i) { return color(i); });


In this code snippet, the color scale is defined using d3.scaleOrdinal().range() with an array of color values. Then, in the path elements of the donut chart, the color is set using the fill attribute by accessing the color scale with the index i. This will assign a different color to each segment of the donut chart based on the index of the data element.