D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
tak7iji
Full window
Github gist
Bar chart (use scalePoint)
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; } </style> </head> <body> <div id="bar-chart"> <svg width="800" height="600"> <g class="chart" transform="translate(40,40)"> <g class="x-axis" transform="translate(0,400)"/> <g class="y-axis"/> </g> </svg> </div> <script> var data = [ {key:"data1", value:336}, {key:"data2", value:98}, {key:"data3", value:79}, {key:"data4", value:60}, {key:"data5", value:30} ]; var yScale = d3.scaleLinear() .domain([0,d3.max(data, function(d){ return d.value; })]) .range([400,0]) var xScale = d3.scalePoint() .domain(data.map(function(d){return d.key})) .rangeRound([0,60]) .padding(0.1) //console.log(data.map(function(d){return d.key})) //console.log(d3.range(data.length)) console.log(d3.max(xScale.range(),function(d){return d})) console.log(data.length) width = d3.max(xScale.range(),function(d){return d}) / (data.length + 1) var xAxis = d3.axisBottom(xScale); d3.select(".x-axis") .call(xAxis) .selectAll('text') .attr('dx','-2em') .attr('dy','.15em') .attr("transform", "rotate(-65)"); var yAxis = d3.axisLeft(yScale).ticks(20) d3.select(".y-axis") .call(yAxis) var chartHolder = d3.select("#bar-chart .chart"); var bars = chartHolder .selectAll(".bar") .data(data); bars = bars.enter() .append('rect') .classed('bar', true) .attr('width', width) .attr('height', function(d){ return 400 - yScale(d.value) }) .attr('y', function(d){ return yScale(d.value); }) .attr('x', function(d){ return xScale(d.key); }); bars.exit() .remove(); </script> </body>
https://d3js.org/d3.v4.min.js