Multi-Line Graph: Applying Colors and Legend
Learn to add colors and legends to your multi-line graphs.
We'll cover the following...
Applying the colors
Making sure that the colors that are applied to our lines (and ultimately our legend text) are unique from line to line is actually pretty easy.
The changes that we will make to our code are captured in the following code snippet.
// set the colour scalevar color = d3.scaleOrdinal(d3.schemeCategory10);// Loop through each symbol / keydataNest.forEach(function(d,i) {svg.append("path").attr("class", "line").style("stroke", function() { // Add the colours dynamicallyreturn d.color = color(i); }).attr("d", priceline(d.value));});
Firstly, we need to declare an ordinal scale for our colours with var color = d3.scaleOrdinal(d3.schemeCategory10);
. This is a set of categorical colors (10 of them in this case) that can be invoked, which are a nice mix of differences from each other and pleasant on the eye.
We then use the color scale to assign a unique stroke (line color) for each unique key (symbol) in our dataset.
.style("stroke", function() {
return d.color = color(i); })
It seems easy when it’s implemented. But in all reality, it is the product of some very clever thinking behind the scenes when designing D3.js and even picking the colors that are used. The ...