如果列名为=,则为颜色值指定颜色

时间:2013-06-26 16:16:18

标签: d3.js

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

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列名是意大利政治家的名字 - 我有一个数组定义每个政治家的颜色 - 我需要合并这些数据,如果列名是=数组中的政治家名称,我想使用这种颜色而不是颜色(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”有效,您有什么建议吗?

由于 丹尼尔 附: 抱歉英文不好

2 个答案:

答案 0 :(得分: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); }

答案 1 :(得分: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; })