0

我正在制作一个多线图,现在我正在定义这样的颜色

color = d3.scale.ordinal()
  .range(["rgba(255,255,255,0.90)", "rgba(0,0,0,0.20)","rgba(255,255,255,0.70)", "rgba(0,0,0,0.40)", "rgba(255,255,255,0.50)", "rgba(0,0,0,0.60)", "rgba(255,255,255,0.30)", "rgba(0,0,0,0.80)"]);

为行分配颜色,我使用以下代码:

var tracciato = svg.selectAll(".line-group")
    .data(column)
  .enter().append("g")
    .attr("class", function(d, i) { return i +" line-group"; });

tracciato.append("path")
    .attr("class", "line")
    .attr("d", function(d) { return line(d.values); })
    .style("stroke", function(d) { return color(d.name)})

如果列名值等于某个值,我需要覆盖此颜色分配... - 我有一个列名是意大利政治家姓名的 csv - 我有一个定义每个政治家颜色的数组 - 我需要合并这些数据和如果列名 = 数组中的政客姓名,我想使用这种颜色而不是 color(d.name) 我写了这段代码,但它不起作用......

var colore= [{  nome: 'renzi',col: '#ff0000'},{nome: 'berlusconi',col: '#0000ff'}]   

tracciato.append("path")
    .attr("class", "line")
    .attr("d", function(d) { return line(d.values); })
    .style("stroke", function(d) { 
    //if color array exist 
    if(colore != undefined){
        col_nome=d.name; //name of the column in the csv
        //I want to iterate through the array 
        for (var a = 0; a <= colore.length - 1; a++) {
          //and check if the col_name is = to array[a].nome
          if (col_nome.toLowerCase().indexOf(colore[a].nome) >= 0) {
              return colore[a].col;//if yes, use the color defined in the arry
            }
          else{return color(d.name);};//if not, use the standard color
        };


      }
      //if color array doesn't exist use standard color
      else{return color(d.name);}
    })

问题是 for 没有执行但只吃一次午餐,所以检查只针对 colore[0].nome 你有什么建议可以让“for”工作吗?

谢谢 Daniele 对糟糕的英语感到抱歉

4

2 回答 2

0

您的for循环只运行一次,因为无论比较结果如何,您都将从它返回。你想要的功能看起来像这样。

if(colore != undefined){
    col_nome=d.name;
    for (var a = 0; a <= colore.length - 1; a++) {
      if (col_nome.toLowerCase().indexOf(colore[a].nome) >= 0) {
          return colore[a].col;
      }
    }
    return color(d.name);
 }
 else{ return color(d.name); }
于 2013-06-26T16:34:42.413 回答
0

我认为如果您删除,您的代码将起作用:

else{return color(d.name);};//if not, use the standard color

所以如果名称不匹配,循环将不会提前返回colore[0].nome

不过,只是为了好玩,我用更惯用的 d3 重写了你的函数:

.style("stroke", function(d) { 
  index = colore.map(function(d){ return d.nome; }).indexOf(d.name.toLowerCase());
  return (index == -1) ? color(d.name) : colore[index].col; })
于 2013-06-26T16:35:51.810 回答