问题描述:

I am using the D3 library to create a Zoomable Treemap for my application data using Javascript and JSON. I see online that many times d3 category for Color is being used to determine the colors of each section. However, I wish to color the sections of treemap using my application logic. Like below:

If conditionA

color = red

If conditionB

color=green

....

Is there any way to achieve this.. Check the values of my JSON Object and set the color of a section only on the basis of some conditions; and have all other sections set to a default color?

网友答案:

Your question is a little vague (next time include some code!), but in general, say you have data like this:

var data = [{
  conditionA: true,
  conditionB: false
}, {
  conditionA: false,
  conditionB: true
}, {
  conditionA: false,
  conditionB: false
}];

then it's as simple as:

svg.selectAll('.SomeCircles')
  .data(data)
  .enter()
  .append('circle')
  .attr('r', 20)
  .attr('cx', function(d, i) {
    return i * 25 + 25;
  })
  .attr('cy', function(d, i) {
    return i * 25 + 25;
  })
  .attr('class', 'SomeCircles')
  .style('fill', function(d) { //<-- filling based on an attribute of my data
    if (d.conditionA) {
      return 'red';
    } else if (d.conditionB) {
      return 'green';
    } else {
      return 'blue';
    }
  });

Here is an example.

相关阅读:
Top