D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
officeofjane
Full window
Github gist
Dot histogram
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"></script> <style> body { font-family: "avenir next", Arial, sans-serif; font-size: 12px; margin: 0; } .chart { max-width: 700px; margin: 0 auto; } </style> </head> <body> <div class='chart'></div> <script> const margin = { top: 10, right: 50, bottom: 30, left: 50 }; const width = 700 - margin.left - margin.right; const height = 500 - margin.top - margin.bottom; // $ to indicate DOM element const $chart = d3.select('.chart'); const $svg = $chart.append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom); const $plot = $svg.append('g') .attr('transform', `translate(${margin.left}, ${margin.top})`); // set up scales and histogram layout const x = d3.scaleLinear() .rangeRound([0, width]); const xAxis = d3.axisBottom(); function setupChart(data) { const sortedData = data.map(d => { let alliance_code = null; if (d.winning_party_alliance == 'NA') { alliance_code = 'zOther'; } else { alliance_code = d.winning_party_alliance; } return { ...d, pc_vote_won: +d.pc_vote_won/100, order: alliance_code } }) sortedData.sort((x, y) => { return d3.ascending(x.order, y.order) }) x.domain(d3.extent(sortedData, d => d.pc_vote_won)).nice(); xAxis.scale(x).ticks(10); // calculate number of 0.01 bins in the histogram const xMin = Math.round(d3.min(sortedData, d => d.pc_vote_won)*100)/100; const xMax = Math.round(d3.max(sortedData, d => d.pc_vote_won)*100)/100; const nbins = (xMax-xMin)/0.01; console.log({xMin, xMax}); const histogram = d3.histogram() .domain(x.domain()) .thresholds(x.ticks(nbins)) .value(d => d.pc_vote_won) // apply histogram generator to values const binData = histogram(sortedData); const $bins = $plot.selectAll('.bins') .data(binData) .enter() .append('g') .attr('class', 'bins') .attr('transform', d => `translate(${x(d.x0)}, ${height})`) $bins.selectAll('circle') .data(d => d.map((p, i) => { return { idx: i, name: p.constituency, alliance: p.winning_party_alliance, value: p.pc_vote_won, radius: 5 } })) .enter() .append('circle') .attr('class', 'constituency') .attr('id', d => d.name) .attr('cx', 0) .attr('cy', d => - d.idx * 2 * d.radius - d.radius) .attr('r', d => d.radius - 0.5) .attr('fill', d => { if (d.alliance === 'National Democratic Alliance') { return 'orange' } else if (d.alliance === 'United Progressive Alliance') { return 'green' } else { return '#dcdcdc' } }) $plot.append('g') .attr('class', 'axis x') .attr('transform', `translate(0, ${height})`) .call(xAxis); } function init() { d3.csv('india-election-2019-results.csv') .then(setupChart); } init(); </script> </body>
https://d3js.org/d3.v5.min.js