D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
rjmundt
Full window
Github gist
rect with labels
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; } text{ font-family: Avenir; } </style> </head> <body> <script> //global var var w=300 var h=500 var rowHeight=50 var gap=10; var colors=["red","green","purple","beige"] var margin={ left:100, top:80 } //create svg element var svg = d3.select("body").append("svg") .attr("width", w) .attr("height", h) //declare svg element svg.append("rect") .attr("width", w) .attr("height", h) .attr("fill","lightgray") var myData = [ {name:"Michael",value:35}, {name:"Ryan",value:45}, {name:"Alan",value:55}, {name:"David",value:65} ] //create new group and append rects to it var rects = svg.append("g").attr("id","rects") .selectAll("rect") .data(myData) .enter() .append("rect"); //geometry and style the rects rects.attr("height",rowHeight-gap) .attr("x",margin.left) .attr("width",0) .attr("y",function(d,i){ return margin.top+(i*rowHeight); }) .attr("fill",function(d,i){ return colors[i]; }) rects.transition() .delay(1000) .duration(1000) .attr("width",function(d,i){ return d.value; }) var labels = svg.append("g").attr("id","labels") .selectAll("text") .data(myData) .enter() .append("text"); //position of text labels.attr("x",margin.left-5) .attr("y",function(d,i){ return margin.top+(i*rowHeight)+(rowHeight/2); }) .text(function(d,i){ return d.name }) .attr("text-anchor","end") </script> </body>
https://d3js.org/d3.v4.min.js