How to draw pie chart with custom color in d3.js?

Member

by orpha , in category: Javascript , 4 months ago

How to draw pie chart with custom color in d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 4 months ago

@orpha 

To draw a pie chart with custom colors in d3.js, you can follow these steps:

  1. Define the data for the pie chart. This data should be an array of objects, where each object represents a slice of the pie chart. Each object should have a "label" property representing the label of the slice and a "value" property representing the size of the slice.
1
2
3
4
5
var data = [
    { label: "A", value: 30 },
    { label: "B", value: 20 },
    { label: "C", value: 50 }
];


  1. Define the colors you want to use for each slice of the pie chart. You can define an array of colors and then use a function to assign colors to each slice based on its index.
1
2
3
4
var colors = ["#ff0000", "#00ff00", "#0000ff"];

var color = d3.scaleOrdinal()
    .range(colors);


  1. Create a d3 pie layout and pass in the data array.
1
2
3
4
var pie = d3.pie()
    .value(function(d) { return d.value; });

var pieData = pie(data);


  1. Create an SVG element and append a group element to it to hold the pie chart.
1
2
3
4
5
6
7
var svg = d3.select("body")
    .append("svg")
    .attr("width", 400)
    .attr("height", 400);

var g = svg.append("g")
    .attr("transform", "translate(200,200)");


  1. Create a path element for each slice of the pie chart and set the "d" attribute using the arc function. Also, set the "fill" attribute with the custom color based on the index of the slice.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var arc = d3.arc()
    .outerRadius(100)
    .innerRadius(0);

g.selectAll("path")
    .data(pieData)
    .enter()
    .append("path")
    .attr("d", arc)
    .attr("fill", function(d, i) {
        return color(i);
    });


  1. Add labels for each slice of the pie chart by appending text elements to the SVG element.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
g.selectAll("text")
    .data(pieData)
    .enter()
    .append("text")
    .attr("transform", function(d) {
        return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text(function(d) {
        return d.data.label;
    });


  1. Your pie chart with custom colors should now be displayed on the webpage. You can customize the colors, sizes, and other properties as needed.