Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3js - d3.scale.category10() not working?

I add d3js to my new project:

and do a simple test just to make sure it works:

d3.select(".d3div").transition()
    .duration(750)
    .style("background-color", "black");

this work. However:

var colors = d3.scale.category10().domain([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

this give error:

myd3.js:1 Uncaught TypeError: Cannot read property 'category10' of undefined

and I try some other function too:

d3.scale.linear()

have some errors:

myd3.js:3 Uncaught TypeError: Cannot read property 'linear' of undefined

if I change the import to

<script src="https://d3js.org/d3.v3.js"></script>

then it works for the functions, but the transition animation not working anymore.

I want to use the latest version. but it seems like there are scope changes that I am not aware of.

How can I resolve this?

like image 529
sooon Avatar asked Dec 16 '16 05:12

sooon


2 Answers

There is no more d3.scale.category in D3 v4.x.

According to the changelog, here are the changes:

d3.scale.category10 ↦ d3.schemeCategory10
d3.scale.category20 ↦ d3.schemeCategory20
d3.scale.category20b ↦ d3.schemeCategory20b
d3.scale.category20c ↦ d3.schemeCategory20c

These are color schemes that...

... are designed to work with d3.scaleOrdinal.

So, instead of d3.scale.category10(), you'll have to use:

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

Here is the documentation for the category scales: https://github.com/d3/d3-scale#schemeCategory10

PS: You don't need to set the domain for an ordinal scale like this. Check this demo:

var data = d3.range(10);

var svg = d3.select("svg");

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

var circles = svg.selectAll(".circles")
	.data(data)
	.enter()
	.append("circle")
	.attr("cx", d=>10+d*25)
	.attr("cy", 50)
	.attr("r", 10)
	.attr("fill", d=>color(d));
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
like image 84
Gerardo Furtado Avatar answered Nov 13 '22 04:11

Gerardo Furtado


In d3v4, you need to use d3.schemeCatgory:

var colors = d3.scaleOrdinal(d3.schemeCategory10);
like image 2
philantrovert Avatar answered Nov 13 '22 04:11

philantrovert