Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the d3.js v4.0 equivalent for d3.scale.category10()?

Tags:

d3.js

I'm trying to learn d3 with the Interactive Web Visualization book, but a lot has changed with version 4.0. One thing I really can't figure out is if there is an equivalent for d3.scale.category10() to get an easy mapping to colors. Is there something like that in the new version or do we need to use math.random and code up something ourselves?

like image 555
anonygrits Avatar asked Jul 15 '16 08:07

anonygrits


2 Answers

Instead of

d3.scale.category10()

use

d3.scaleOrdinal(d3.schemeCategory10);

Create a color scale like this:

var color = d3.scaleOrdinal(d3.schemeCategory10);

use the color like this in the code same as in V3:

svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 100)
.style("fill", color(3))

read here

Reference here

working code here

like image 90
Cyril Cherian Avatar answered Oct 23 '22 16:10

Cyril Cherian


A straight-forward solution is to use the following color scales in version-4 of d3.js :

var colorScale_1 = d3.schemeCategory10;
var colorScale_2 = schemeCategory20;
var colorScale_3 = d3.schemeCategory20b;
var colorScale_4 = d3.schemeCategory20c;

colorScale_1, colorScale_2, colorScale_3, colorScale_4 are the arrays of different colors. So, you can use their different indices to fill the shape. For example

svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 100)
.style("fill", colorScale_1[2])

For reference, take a look here: http://bl.ocks.org/emmasaunders/f4902478bcfa411c77a412c02087bed4

Hope that helps.

like image 3
shwetabharti Avatar answered Oct 23 '22 16:10

shwetabharti