Question

[Solved] 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?

Enquirer: sooon

||

Solution #1:

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>

Respondent: Gerardo Furtado

Solution #2:

In d3v4, you need to use d3.schemeCatgory:

var colors = d3.scaleOrdinal(d3.schemeCategory10);
Respondent: philantrovert

Solution #3:

if someone using angular 2

 var colorScale=d3Scale.scaleOrdinal(d3.schemeCategory10);

this is the correct way.

Respondent: sajal rajabhoj

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy