D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
joebynoeAccenture
Full window
Github gist
The Best Bar Chart Ever Updating
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; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .bar { fill: steelblue; } </style> </head> <body> <script> //var = [1,2,3,4,5] var data = [{x: "A", y: 10, color: "green"},{x: "B", y: 12, color: "orange"},{x: "C", y: 10, color: "green"},{x: "D", y: 9, color: "red"}]; var margin={top: 20, right: 30, bottom: 30, left: 30}; var width = 960 - margin.left -margin.right; var height = 500 - margin.top - margin.bottom; var svg = d3.select("body").append("svg") .attr({ width: width + margin.left + margin.right, height: height + margin.top + margin.bottom }); //.style("background-color", "green") var g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var axis_x = d3.scale.ordinal().rangeRoundBands([0, width], 0.1, 0.2); var axis_y = d3.scale.linear().range([height, 0]); function draw(newData){ d3.selectAll(".axis").remove(); axis_y.domain([0, d3.max(newData.map(function(d){return d.y}))]); axis_x.domain(newData.map(function(d){ return d.x})); g.append("g") .attr("class", "y axis") .call(d3.svg.axis().scale(axis_y).orient("left")); g.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(d3.svg.axis().scale(axis_x).orient("bottom")); //SELECTION var bars = g.selectAll(".bar").data(newData); //ENTERING var barEntering = bars.enter() .append("rect") .attr("class", "bar"); //ATTRIBUTES bars .attr({ x: function(d){ return axis_x(d.x)}, //y: function(d){ return axis_y(d.y)}, width: axis_x.rangeBand(), // height: function(d){ return height - axis_y(d.y)} }) .transition() .duration(500) .attr({ y: function(d){ return axis_y(d.y)}, height: function(d){ return height - axis_y(d.y)} }); //EXITING var barsExiting = bars.exit().remove(); } setInterval(function(){ draw([{x: "A", y: Math.random()*10, color: "green"},{x: "B", y: Math.random()*10, color: "orange"},{x: "C", y: Math.random()*10, color: "green"},{x: "D", y: Math.random()*10, color: "red"}]) }, 1000) </script> </body>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js