D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
peterchappell
Full window
Github gist
me bar chart
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> const margin = { top: 80, bottom: 50, right: 20, left: 50 } var width = 500 - margin.left - margin.right; var height = 500 - margin.top + margin.bottom; var chartData = [ { value: 153, category: 'Whatsit', color: 'blue' }, { value: 25, category: 'Thingy', color: 'green' }, { value: 76, category: 'WTFs', color: 'orange' }, { value: 200, category: 'Thingamajiggy', color: 'purple' }, { value: 300, category: 'Meh', color: 'turquoise' } ] var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .attr('style', 'background-color: #f5f5f5') var g = svg.append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.right + ')') var maxValue = d3.max(chartData, function(d) { return d.value }) var y_scale = d3.scale.linear() .domain([0, maxValue]) .range([height, 0]) var x_scale = d3.scale.ordinal() .domain(chartData.map(function(d) { return d.category})) .rangeRoundBands([0, width], 0.1, 0) var bars = g.selectAll('rect.bar').data(chartData) bars.enter().append('rect') .attr({ class: 'bar', x: function(d, i) { //return i * barWidth return x_scale(d.category) }, y: function(d, i) { return y_scale(d.value) }, height: function(d, i) { return height - y_scale(d.value) }, width: function(d,i) { return x_scale.rangeBand(d.category) }, style: function(d, i) { return 'fill: ' + d.color } }) bars.exit().remove(); var yAxis = d3.svg.axis() .scale(y_scale) .orient('left') var xAxis = d3.svg.axis() .scale(x_scale) .orient('bottom') g.append('g') .attr('class', 'y-axis axis') .call(yAxis) g.append('g') .attr('class', 'x-axis axis') .attr('transform', 'translate(0, ' + height + ')') .call(xAxis) g.append('text') .text('My first D3 bar chart!') // todo: 200 should be width/2 .attr('transform', 'translate(200, ' + (height + 70) + ')') .attr('style', 'font-size:1.5em; text-anchor: middle') // var labels = g.selectAll('text.label').data(chartData) // labels.enter().append('text') // .attr({ // class: 'label', // y: height + 30, // x: function(d, i) { // return x_scale(d.category) + x_scale.rangeBand(d.category)/2 // }, // width: function(d,i) { // return x_scale.rangeBand(d.category) // }, // style: 'text-anchor: middle' // }) // .text(function(d, i) { // return d.category // }) </script> </body>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js