D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
chowzzzz
Full window
Github gist
D3 Fundamentals - Colouring Bar Chart
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>Drawing SVG Shapes with D3</title> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> var w = 300; var h = 100; var padding = 2; var dataset = [5, 10, 14, 20, 25]; var svg = d3.select("body").append("svg") .attr("width", w) .attr("height", h); // function to add a specific color/KPI indicator function colorPicker(v){ // v as value if(v <= 20) { return "#666666" } else if (v > 20) { return "#FF0033"} } // Build bar chart svg.selectAll("rect") // Take all the rect and create new ones .data(dataset) // for all the diff elements in dataset .enter() // If there aren't any on the page, create them .append("rect") // Append rect .attr("x", function(d, i) {return i * (w / dataset.length);}) .attr("y", function(d) { return h - (d * 4); }) .attr("width", w / dataset.length - padding) .attr("height", function(d) { return d * 4; }) // Colour using data .attr("fill", function(d) { return "rgb(0, 0," + (d * 10) + ")";}) // Colour using the function above .attr("fill", function(d) { return colorPicker(d); }) </script> </body>
https://d3js.org/d3.v4.min.js