D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
DDDDDanica
Full window
Github gist
Final bar chart with animation
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> .oaas-bar { /* text-align:center; */ } .oaas-bar-input { margin: 2%; } .oaas-bar-chart { margin: 2%; /* display: table; margin: 0 auto; */ width:600px; height: 40px; border: 1px solid rgba(64,66,79,.5); border-radius: 10px; } </style> </head> <body> <div class="oaas-bar"> <div class="oaas-bar-input"> Total Expense For This Month:1825<br/> Total Budget For This Month: <input class="oaas-bar-input"></input></div> <div class="oaas-bar-chart"></div> </div> <script> let cost = 1825; let budget = 2203; let ratio = (cost/budget).toFixed(2); dataset = [{"label": "a", "value": ratio}]; //Width and height let w = 600; let h = 40; //Create SVG element let svg = d3.select(".oaas-bar-chart") .append("svg") .attr("class","oaas-bar-chart-svg") .attr("width", w) .attr("height", h); let xscale = d3.scaleLinear() .domain([0,1]) .range([0,w]); let bars = svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("rx", 10) .attr("ry",10) .attr("y", (d, i)=> { return 0; }) .attr("x", 0) .attr("width", 1) .attr("height", 40) .attr("fill", (d) => { let value = d.value; switch (true) { case (value > 1): return "#ef473d"; break; case (value > 0.8): return "#fbb316"; break; default: return "#42c0c0"; } }) .style("opacity", "0.6"); bars.transition() .duration(1000) .delay(100) .attr("width", (d) => { return xscale(d.value); }) let text = svg.selectAll("text").data(dataset) .enter() .append("text") .attr("x",function(d) { return xscale(d.value)/2 - 12; }) .attr("y",h/2 + 3) .text("Total Expense: £" + cost) .style("fill", "#40424f"); </script> </body>
https://d3js.org/d3.v4.min.js