D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
sogokyo
Full window
Github gist
20170512 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> text {font-family:Avenir-Light; font-size:14px}; body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> //global variables var h=300; var w=300 ; var rowHeight=40; var gap=10 ; var colors=["red","teal","olive","darkorange","darkpink"] var margin={ left:70, top:65 } //create new svg element var svg = d3.select("body").append("svg") .attr("width",w) .attr("height",h) svg.append("rect") .attr("width",w) .attr("height",h) .attr("fill","#dcdcdc") //declare data var myData = [ {name:"Michael",value:35}, {name:"Ryan",value:50}, {name:"Alan",value:75}, {name:"David",value:90} ] //create new group and append rects to it var rects=svg.append("g").attr("id","rects") .selectAll("rects") .data(myData) .enter() .append("rect") //geomoetry 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]; }) //create some labels for the bars var labels=svg.append("g").attr("id","labels") .selectAll("text") .data(myData) .enter() .append("text") //position labels and write text labels.attr("x",margin.left-5) .attr("y", function(d,i){ return margin.top+(i*rowHeight)+(rowHeight/2)-(gap/5); }) .text(function(d){ return d.name }) .attr("text-anchor","end") rects.transition() .duration(1000) .delay(function(d,i){ return i*500 }) .attr("width",function(d,i){ return d.value*2; }) // var svg = d3.select("body").append("svg") // .attr("width",w) // .attr("height",h/2) // svg.append("rect") // .attr("width",w) // .attr("height",h) // .attr("fill","grey") // .attr("y", function(d,i){ // return margin.top+(i*rowHeight) // }) </script> </body>
https://d3js.org/d3.v4.min.js