Grund
Grund

Reputation: 309

How bind color with data in D3.js?

i need some help. I am working on pie chart and need bind currency to accurate color I have perhaps this JSON

      [{'rate': 24, 'currency': 'EUR'},
        {'rate': 32, 'currency': 'USD'},
        {'rate': 13, 'currency': 'GB'}
       ];

and these array of colors:

 colors = ['red', 'green','blue'];

so in my d3 chart pie i want bind currency to right color, to EUR bind blue to USD bind red to GB bind green;

how can i do this ?

making pie chart's path code is:

 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);
                        });

Upvotes: 2

Views: 687

Answers (2)

domyos
domyos

Reputation: 153

Although Cyrils answer works it can result in quite a lot of if-else-blocks. A different approach would be to use a ordinal scale like this:

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

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

Upvotes: 1

Cyril Cherian
Cyril Cherian

Reputation: 32327

Do this way:

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];
                        });

Upvotes: 1

Related Questions