D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
dukevis
Full window
Github gist
Add Value Bar Chart on Click
<!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-padding],0.05); var yScale = d3.scale.linear() .domain([0,d3.max(dataset,function(d){ return d; })]) .range([h-padding,padding]); 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); } dataset.push( Math.floor( Math.random()*yRange ) ); yScale = d3.scale.linear() .domain([0,d3.max(dataset,function(d){ return d; })]) .range([h-padding,padding]); xScale = d3.scale.ordinal() .domain(d3.range(dataset.length)).rangeRoundBands([0,w-padding],0.05); var bars = svg.selectAll("rect") .data(dataset); bars.enter() .append("rect") .attr("x",w) .attr("y",function(d){ return yScale(d)-padding-5; }) .attr("height",function(d){ return h-yScale(d); }) .attr("fill",function(){ return "rgb(255,255,255)"; }) .attr("width",xScale.rangeBand()); xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); yAxis = d3.svg.axis() .scale(yScale) .orient("left"); //orientation for labels svg.select(".x.axis") .transition() .duration(1000) .call(xAxis); svg.select(".y.axis") .transition() .duration(1000) .call(yAxis); bars.transition() .duration(1000) .delay(function(d,i){ return i*50; }) .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); }) .attr("x",function(d,i){ return xScale(i)+padding; }) .attr("width",xScale.rangeBand()); }); </script> </body> </html>