create pie chart using d3js

ht‮‬tps://www.theitroad.com

Here is an example of creating a pie chart using D3.js:

// Define the dimensions of the chart
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
    width = 600 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

// Create the SVG object and set its dimensions
var svg = d3.select("body")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// Define the data for the chart
var data = [
  {name: "Apples", value: 10},
  {name: "Bananas", value: 20},
  {name: "Oranges", value: 15},
  {name: "Grapes", value: 5},
  {name: "Pineapples", value: 25}
];

// Set up the color scale
var color = d3.scaleOrdinal()
  .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"]);

// Define the arc for the pie slices
var arc = d3.arc()
  .outerRadius(Math.min(width, height) / 2 - 10)
  .innerRadius(0);

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

// Create the pie chart
var g = svg.selectAll(".arc")
  .data(pie(data))
  .enter().append("g")
    .attr("class", "arc");

g.append("path")
  .attr("d", arc)
  .style("fill", function(d) { return color(d.data.name); });

g.append("text")
  .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
  .attr("dy", ".35em")
  .text(function(d) { return d.data.name; });

In this example, we define the dimensions of the chart and create an SVG object to contain it. We then define an array of data for the chart, with each object representing a single slice of the pie.

Next, we set up the color scale, arc, and pie layout. The color scale is set up using the d3.scaleOrdinal() function and assigns colors to each slice of the pie. The arc is defined using the d3.arc() function and sets the outer and inner radius of each slice. The pie layout is defined using the d3.pie() function and sorts the slices based on the order of the data array.

To create the pie chart, we first select all .arc elements in the SVG object and bind the pie data to them using the .data(pie(data)) method. We then create a g element for each slice of the pie using .enter().append("g") and set the class to arc.

For each slice, we create a path element using the arc function and set the fill color based on the color scale. We then add a text element to each slice and position it using the arc.centroid() function.