Uncaught TypeError: d3.schemeCategory20 is not a function

会有一股神秘感。 提交于 2020-01-04 03:39:10

问题


I'm new in d3js and all the javascript-world too. In my html-file I simply import the script like that:

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

By trying to use following:

var ordinalColorScale = d3.schemeCategory20();

I get the exception

Uncaught TypeError: d3.schemeCategory20 is not a function at index.html:48

Do I need any other d3js module, which has to be imported? Or what could have caused the problem?


回答1:


d3.schemeCategory20 is neither a scale nor a function. It is just an array of colours. According to the API, it is...

An array of twenty categorical colors represented as RGB hexadecimal strings.

The same API says:

These color schemes are designed to work with d3.scaleOrdinal.

Therefore, you have to pass it to an ordinal scale as its range, like this:

var myScale = d3.scaleOrdinal()
    .range(d3.schemeCategory20)

Which is the same of:

    var myScale = d3.scaleOrdinal(d3.schemeCategory20)

Here is a demo:

var scale = d3.scaleOrdinal(d3.schemeCategory20);

d3.select("body").selectAll(null)
  .data(d3.range(20))
  .enter()
  .append("div")
  .style("background-color", function(d){ return scale(d)})
div {
  min-height: 10px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>



回答2:


For d3 v4. You can use like as

   var color = d3.scaleOrdinal(d3.schemeCategory20c);
                     or
    var color = d3.scaleOrdinal()
      .range(["red", "green", "blue", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);



回答3:


d3.schemeCategory20 it is exactly not a function. It is an array of default colors. You should pass this array to your scale function.

console.log('d3.schemeCategory20 ==> ', d3.schemeCategory20);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>



回答4:


For anyone who is looking for it in future d3 versions and also something to consider when using this color scheme. Changes in D3 5.0:

D3 no longer provides the d3.schemeCategory20* categorical color schemes. These twenty-color schemes were flawed because their grouped design could falsely imply relationships in the data: a shared hue can imply that the encoded data are part of a group (a super-category), while relative lightness can imply order

from d3/CHANGES.md



来源:https://stackoverflow.com/questions/47052915/uncaught-typeerror-d3-schemecategory20-is-not-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!