Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get red color of schemeCategory10

I'm tying to get the red color (or any color) of the schemeCategory10. I tried this:

var colors = d3.scaleOrdinal(d3.schemeCategory10);
colors(1);

But I always get the same color (orange) when I change the number into the function colors.

How can I get red instead of orange ? How does it work?

like image 217
C Taque Avatar asked Jan 30 '23 18:01

C Taque


1 Answers

In an ordinal scale, if you don't set the domain explicitly, the domain will be inferred from the values you pass. The API is very clear regarding this:

Setting the domain on an ordinal scale is optional if the unknown value is implicit (the default). In this case, the domain will be inferred implicitly from usage by assigning each unique value passed to the scale a new value from the range.

Therefore, if you don't set the domain, the scale will return values in a first-come, first-served basis.

Now, let's have a look at d3.schemeCategory10:

enter image description here

As you can see, red is the forth colour. So, to get the red...

var colours = d3.scaleOrdinal(d3.schemeCategory10)
	.domain(["foo", "bar", "baz", "foobar"]);
  
console.log(colours("foobar"))
<script src="https://d3js.org/d3.v4.min.js"></script>

... we have to set our domain (this is the most important part) and, after that, we just have to pass the fourth item in that domain. Here is another demo:

var colours = d3.scaleOrdinal(d3.schemeCategory10)
  .domain(["foo", "bar", "baz", "foobar"]);

d3.select("p").style("color", colours("foobar"))
<script src="https://d3js.org/d3.v4.min.js"></script>
<p>This was a black text... now it is red.</p>

PS: You should get always "blue" (which is the first colour), not "orange". That means that you already used the scale somewhere else in the code... then, when you use it again, you get "orange" (the second colour). The fact that you're using 1, which is the index of the "orange" (the second colour), makes no difference. Have a look:

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

d3.select("p").style("color", colours(1))
<script src="https://d3js.org/d3.v4.min.js"></script>
<p>This text should be orange, but in fact it is blue.</p>
like image 198
Gerardo Furtado Avatar answered Feb 03 '23 07:02

Gerardo Furtado