Built with blockbuilder.org
forked from chowzzzz's block: D3 Fundamentals - Colouring Bar Chart
forked from chowzzzz's block: 4 D3 Fundamentals - Adding Labels
xxxxxxxxxx
<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 = 120;
var padding = 2;
var dataset = [5, 10, 13, 20, 25, 11, 25, 22, 18, 7];
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"}
}
// 2 - 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; })
// 3 - Colour using data
.attr("fill", function(d) { return "rgb(0, 0," + (d * 10) + ")";})
// 3 - Colour using the function above
.attr("fill", function(d) { return colorPicker(d); })
// 4 - Add labels (add txt)
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text( function(d) { return d; })
.attr("text-anchor", "middle")
.attr("x", function(d,i) {
return i * (w / dataset.length) + (w / dataset.length - padding) / 2;
})
.attr("y", function(d) { return h - (d * 4) + 14 })
.attr("font-family", "sans-serif")
.attr("font-size", "12")
.attr("fill", "#ffffff");
</script>
</body>
https://d3js.org/d3.v4.min.js