Javascript 如何将颜色与D3.js中的数据绑定?

Javascript 如何将颜色与D3.js中的数据绑定?,javascript,d3.js,Javascript,D3.js,我需要一些帮助。 我正在制作饼图,需要将货币绑定到准确的颜色 我可能有这个问题 [{'rate': 24, 'currency': 'EUR'}, {'rate': 32, 'currency': 'USD'}, {'rate': 13, 'currency': 'GB'} ]; 这些颜色的排列: colors = ['red', 'green','blue']; 因此,在我的d3图表饼图中,我希望将货币绑定到正确的颜色, 包扎蓝色

我需要一些帮助。 我正在制作饼图,需要将货币绑定到准确的颜色 我可能有这个问题

      [{'rate': 24, 'currency': 'EUR'},
        {'rate': 32, 'currency': 'USD'},
        {'rate': 13, 'currency': 'GB'}
       ];
这些颜色的排列:

 colors = ['red', 'green','blue'];
因此,在我的d3图表饼图中,我希望将货币绑定到正确的颜色, 包扎蓝色 绑红 绿色环保

我该怎么做

制作饼图的路径代码为:

 const color = d3.scale.ordinal().range(colors);  
 const path = chartSvg.selectAll('path')
                        .data(pie(data))
                        .enter()
                        .append('path')
                        .attr('d',arc)
                        .attr('fill',function(d,i){
                            return color(d.data.currency);
                        });
这样做:

var colors = ['red', 'green','blue'];
const path = chartSvg.selectAll('path')
                        .data(pie(data))
                        .enter()
                        .append('path')
                        .attr('d',arc)
                        .attr('fill',function(d,i){
                            if (d.data.currency == "EUR")
                             return color[2];
                            if (d.data.currency == "USD")
                             return color[0];
                            if (d.data.currency == "GB")
                             return color[1];
                        });

虽然Cyrils的答案是有效的,但它会导致相当多的if-else块。另一种方法是使用如下顺序量表:

var currencyScale = d3.scale.ordinal()
   .domain(['EUR', 'USD'])
   .range(['red', 'blue']);

path.attr('fill',function(d){
  return currencyScale(d.data.currency);
});

你可以在饼图的填充中写一个if块……你可以在制作饼图的pathcont path=chartSvg的地方发布代码吗?selectAll('path').data(pie(data)).enter().append('path').attr('d',arc).attr('fill',函数(d,i){return color(d.data.currency);});在fill函数中放置一个if块以从数组中返回颜色很多,我正在工作,我理解它。