简体   繁体   English

从对象数组中绘制任意数量的线时,d3.js的唯一颜色

[英]d3.js unique colors when plotting an arbitrary number of lines from an array of array of objects

I am plotting an arbitrary number of lines with the following code, where allLines is an array of arrays of objects such that each array of objects produces a line. 我用以下代码绘制任意数量的行,其中allLines是对象数组的数组,这样每个对象数组都会产生一行。 Right now all the lines are the same color. 现在,所有行都是相同的颜色。 How can I make each one a unique color? 如何使每个颜色都具有独特性? I am looking for an alternative that would not involve shoehorning this into useing nest() 我正在寻找一个不涉及使用nest()

   var lines = d3.select("svg").selectAll(".myLine")
        .data(allLines)

    lines.enter()
        .append("path")
        .attr("class", "myLine")
        .attr("d", tweetLine)
        .attr("fill", "none")
        .attr("stroke", "darkred")
        .attr("stroke-width", 2)

    lines.exit().remove();

    lines.attr("class", "myLine")
        .attr("d", tweetLine)
        .attr("fill", "none")
        .attr("stroke", "darkred")
        .attr("stroke-width", 2)

You can use one of the predefined scales , eg d3.scale.category20() . 您可以使用预定义比例之一 ,例如d3.scale.category20() You use it like any other D3 scale: 您可以像使用任何其他D3秤一样使用它:

var colours = d3.scale.category20();
colours(someData);
colours(someOtherData);

For your lines, you have an array as the data, so that won't work directly. 对于您的行,您有一个数组作为数据,因此不能直接使用。 However, you can compute something based on the values for the lines and use that, eg 但是,您可以根据这些线的值计算出一些值并使用它,例如

.attr("stroke", function(d) {
  return colors(d3.sum(d, function(e) {
    return e.whateverTheNumberThatDeterminesTheLineIs;
  }));
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM