D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
CoreyBurkhart
Full window
Github gist
Pie Chart
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } .arc text { fill: white; font-weight: bold; } .arc. path { stroke: red; /* stroke-width: 2; */ } .title { font-size: 1.5rem; font-weight: 700; /* text-decoration: underline; */ text-transform: Capitalize; } </style> </head> <body> <script> // Feel free to change or delete any of the code you see in this editor! var width = 960, height = 500, margin = 50, colors = [ 'rgba(142, 68, 173,1.0)', 'rgba(41, 128, 185,1.0)', 'rgba(22, 160, 133,1.0)' ], classes = ['1st Class', '2nd Class', '3rd Class']; var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) var title =svg.append('g') .append('text') .attr('class', 'title') .text('class distribution among titanic survivors') var TITLE_LENGTH = Number.parseInt(title.style('width').substr(0,3)) //center the title over the chart (I know i did this the hardway) title.attr('transform', `translate(${(width / 2) - (TITLE_LENGTH / 2)}, ${margin})`) var chart = svg.append('g') .attr('transform', `translate(${width / 2}, ${height / 1.8})`) var arc = d3.arc() .innerRadius(1) .outerRadius(200) .padRadius(20) var pie = d3.pie() .padAngle(.1); d3.csv('Titanic.csv', function(d) { var survivors = d.filter(function(el) { if(Number.parseInt(el.Survived)) { return el } }) var NUM_1_CLASS = survivors.filter(function(el) { if(el.PClass === '1st') { return el } }).length var NUM_2_CLASS = survivors.filter(function(el) { if(el.PClass === '2nd') { return el } }).length var NUM_3_CLASS = survivors.filter(function(el) { if(el.PClass === '3rd') { return el } }).length var sections = [ NUM_1_CLASS, NUM_2_CLASS, NUM_3_CLASS ]; chart = chart.selectAll('.arc') .data(pie(sections)) .enter() .append('g') .attr('class', 'arc') chart.append('path') .attr('d', arc) .attr('fill', function(d, i) { return colors[i]}) chart.append('text') .attr('transform', function(d){ return `translate(${arc.centroid(d)})`}) .attr('text-anchor', 'middle') .text(function(d, i) {return classes[i]}) }) </script> </body>
https://d3js.org/d3.v4.min.js