D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jwilber
Full window
Github gist
basic reusable bar chart
Built with
blockbuilder.org
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.js"></script> <style> svg { border: 1px dotted red; } </style> </head> <body> <div id="runningHistory"></div> <div id="viz2"></div> </body> <script> var milesRun = [2, 5, 4, 1, 2, 6, 5]; var highTemperatures = [77, 71, 82, 87, 84, 78, 80, 84, 86, 72, 71, 68, 75, 73, 80, 85, 86, 80]; function drawChart(dom, data, options) { const width = options.width || 500; const height = options.height || 300; const barPadding = options.barPadding || 1; const fillColor = options.fillColor || 'steelblue'; var barSpacing = height / data.length; var barHeight = barSpacing - barPadding; var maxValue = d3.max(data); var widthScale = width / maxValue; d3.select(dom).append('svg') .attr('width', width) .attr('height', height) .selectAll('rect') .data(data) .enter() .append('rect') .attr('y', (d,i) => i * barSpacing) .attr('height', barHeight) .attr('x', 0) .attr('width', d => d*widthScale) .attr('fill', fillColor); } var runningOptions = {barPadding: 2, fillColor: 'coral'}; drawChart('#runningHistory', milesRun, runningOptions); const weaOps = {barPadding: 10, fillColor: 'pink', width: 200} drawChart('#viz2', highTemperatures, weaOps) </script> </html>
https://d3js.org/d3.v4.js