D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
dukevis
Full window
Github gist
Bar Transitions with Dynamic Scales
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Title Here</title> <script type="text/javascript" src="../d3.v3/d3.v3.js"></script> <style type="text/css"> .axis path, .axis line{ fill: none; stroke: black; shape-rendering: crispEdges; } .axis text{ font-family:sans-serif; font-size: 11px; } </style> </head> <body> <script type="text/javascript"> var dataset = []; var w=700; var h=505; var padding = 30; var yRange = Math.random()*1000; for(var i =0; i<10; i++){ dataset.push(Math.floor(Math.random()*yRange)); } var svg = d3.select("body") .append("svg") .attr("width",w) .attr("height",h); var cVal = d3.scale.category10(); var xScale = d3.scale.ordinal() .domain(d3.range(dataset.length)).rangeRoundBands([0,w],0.05); var yScale = d3.scale.linear() .domain([0,d3.max(dataset,function(d){ return d; })]) .range([h-padding,padding]); console.log(dataset); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); var yAxis = d3.svg.axis() .scale(yScale) .orient("left"); svg.append("g") .attr("class","x axis") .attr("transform","translate("+padding+","+(h-padding)+")") .call(xAxis); svg.append("g") .attr("class","y axis") .attr("transform", "translate("+padding+","+-10+")") .call(yAxis); svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("y",function(d,i){ return yScale(d)-padding-5; }) .attr("x",function(d,i){ return xScale(i)+padding; }) .attr("height",function(d,i){ return h-yScale(d); }) .attr("width",xScale.rangeBand()) .attr("fill",function(d){ return cVal(d); }); yRange = Math.random()*1000; svg.selectAll("rect") .on("click",function(){ for(var k=0;k<dataset.length;k++){ dataset[k]=Math.floor(Math.random()*yRange); } yScale = d3.scale.linear() .domain([0,d3.max(dataset,function(d){ return d; })]) .range([h-padding,padding]); svg.selectAll("rect") .data(dataset) .transition() .duration(1000) .delay(function(d,i){ return i*100; }) .attr("y",function(d){ return yScale(d)-padding-5; }) .attr("fill",function(d){ return "rgb("+d*2+",0,0)"; }) .attr("height",function(d){ return h-yScale(d); }); svg.selectAll("text").data(dataset).text(function(d){ return d; }) .attr("x",function(d,i){ return xScale(i)+padding; }); console.log(dataset); }); </script> </body> </html>