// Set up the dimensions and margins const width = 600,
height = 600, margin = 50; const radius = Math.min(width,
height) / 2 - margin; // Append SVG element
d3.select("body").append("h2").text("Billionaires by
Category"); const svg = d3.select("body") .append("svg")
.attr("width", width) .attr("height", height) .append("g")
.attr("transform", `translate(${width / 2},${height / 2})`);
// Define color scale const color =
d3.scaleOrdinal(d3.schemeCategory10); // Load data const
csvUrl =
'https://gist.githubusercontent.com/Gorantlavishnusai/f31f9b9f663f94a585c936d4606c385f2fd59dcf2cfe/Billionaires.csv';
d3.csv(csvUrl).then(data => { // Aggregate data by category
const categoryCounts = d3.rollup(data, v => v.length, d =>
d.category); const pieData = Array.from(categoryCounts,
([category, count]) => ({ category, count })); // Create pie
layout const pie = d3.pie().value(d => d.count); const arc =
d3.arc().innerRadius(0).outerRadius(radius); // Draw pie
slices const slices = svg.selectAll(".slice")
.data(pie(pieData)) .enter() .append("g") .attr("class",
"slice"); slices.append("path") .attr("d", arc)
.attr("fill", d => color(d.data.category)) .attr("stroke",
"white") .style("stroke-width", "2px"); // Add labels
slices.append("text") .attr("transform", d =>
`translate(${arc.centroid(d)})`) .style("text-anchor",
"middle") .style("font-size", "12px") .text(d =>
d.data.category); // Add legend const legend =
svg.append("g") .attr("transform", `translate(${radius +
20},${-radius})`) .selectAll(".legend-item") .data(pieData)
.enter() .append("g") .attr("class", "legend-item")
.attr("transform", (d, i) => `translate(0, ${i * 20})`);
legend.append("rect") .attr("width", 15) .attr("height", 15)
.attr("fill", d => color(d.category)); legend.append("text")
.attr("x", 20) .attr("y", 12) .text(d => d.category)
.style("font-size", "12px"); });