d3.csv( 'path/to/cars.csv', // Update this path to the location of your cars.csv file ).then(function (data) { // Group and count by car class var classCounts = {}; data.forEach(function (d) { classCounts[d.class] = (classCounts[d.class] || 0) + 1; }); // Convert data into an array suitable for pie chart var labels = Object.keys(classCounts); var values = Object.values(classCounts); // Set up SVG dimensions var width = 800; var height = 600; var radius = Math.min(width, height) / 3; // Set up color scale var color = d3 .scaleOrdinal() .domain(labels) .range([ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', ]); // Create SVG element var svg = d3 .select('#my_dataviz') .append('svg') .attr('width', width) .attr('height', height) .append('g') .attr( 'transform', 'translate(' + width / 2 + ',' + height / 2 + ')', ); // Generate Pie Chart var pie = d3.pie().value(function (d) { return d; }); var data_ready = pie(values); // Draw slices var arc = d3.arc().innerRadius(0).outerRadius(radius); svg .selectAll('slices') .data(data_ready) .enter() .append('path') .attr('d', arc) .attr('fill', function (d, i) { return color(labels[i]); }) .attr('stroke', 'white') .style('stroke-width', '2px') .style('opacity', 0.7); // Add class names and counts on the pie chart svg .selectAll('labels') .data(data_ready) .enter() .append('text') .text(function (d, i) { return labels[i] + ' (' + values[i] + ')'; }) .attr('transform', function (d) { return 'translate(' + arc.centroid(d) + ')'; }) .attr('text-anchor', 'middle') .attr('font-size', '12px') .style('fill', 'black'); // Legend var legend = svg .selectAll('.legend') .data(labels) .enter() .append('g') .attr('class', 'legend') .attr('transform', function (d, i) { return 'translate(-100,' + (i * 20 - 100) + ')'; }); legend .append('rect') .attr('x', width / 2 - 18) .attr('width', 18) .attr('height', 18) .style('fill', function (d) { return color(d); }); legend .append('text') .attr('x', width / 2) .attr('y', 9) .attr('dy', '.35em') .style('text-anchor', 'start') .text(function (d) { return d; }) .style('font-size', '12px') .style('fill', 'black'); // Optional titles or labels for the chart svg .append('text') .attr('x', 0) .attr('y', height / 2 + 150) .attr('text-anchor', 'middle') .style('font-size', '16px') .text('Car Class Distribution'); });