简体   繁体   中英

Binding color to data in d3

I am copying the 'donut multiples' ( http://bl.ocks.org/mbostock/3888852 ) example from the d3 gallery for a different purpose: to show whether RNA-sequencing of biological samples passed some quality control tests.

So far I have this code: http://tributary.io/inlet/5293726 Apologies for its messiness. You can see from the example that the pie has 22 slices, one for each of the 22 tests (for those interested, 2x11 tests for each sequencing read). I know this isn't the best way to visualize this information, and I am planning to use a stacked bar chart or matrix to show this data, but 1. this can show the biological samples in the layout they were originally collected, in an 8x12 grid (not fixed, need to resize your browser) and 2. this is what I have for now, and learning this concept of binding colors to d3 elements can be used across chart types.

My problem is this: when I bind the data, then the value associated with that element is now 100, and I can no longer access the other objects I created for each row of the cell, namely d.test_colors , which has the colors associated with PASS , WARN , and FAIL for each of the 22 tests.

This is the line I would like to work:

    .style('fill', function (d,i) {
    console.log('in style fill: d', d)
    //          console.log(d.reads.if_experiment);
//    return d.data.test_colors[i];
              return '#A6CEE3'; 
});

Right now it just returns that light blue color, but I want it to return one of the 22 test_colors , hence the i for iterating over the array.

Looking at the 'donut multiples' example, they do some binding of the color domain to the values but I'm not sure how to integrate that into my setup.

Turns out the trick was to pass a list of objects for each 'slice' of the 'donut' that you want, and hold the color information in this object.

The key code is here:

var pie = d3.layout.pie()
    .sort(null)
    .value(function (d) {
    return d.slice;
});
...
d.tests = []
...
(in a for loop)
    d.tests.push({color: r1Colors(d[test]), result: d[test], 
                        slice:100, test_name: test});
...
svg.selectAll(".arc")
    .data(function(d){
      return pie(d.tests); })
    .enter().append('path')
    .attr('class', 'arc')
    .attr('d', arc)
    .style('fill', function (d,i) {
    return d.data.color;
});

Working example: http://tributary.io/inlet/5332310

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM