Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting access to individual area elements with d3

I'm trying to modify the focus+ context example to study the blackbody spectrum with my students.

http://bl.ocks.org/1667367

The problem is that for me the only way to color segment is to plot bar colored charts.

I'd like to do it with the area generator, like this I can have all the benefits of the interpolation when I zoom on.

I can't access to each area element to fill it in the rgb color I want.

Is there any way to acces to the individual area elements and fill it with a function?

Here's my files with an orange filled area(focus) that I'd like to color as I do with the bar chart(context).

http://bl.ocks.org/4345931

In advance thanks.

like image 475
Ben Avatar asked Dec 20 '12 15:12

Ben


1 Answers

I think the right approach here is to use a linearGradient element (specs). You can see my implementation here: http://jsfiddle.net/nrabinowitz/JZACC/

The main point here is that instead of drawing each color as a separate element, you define a gradient of spectrum colors and apply the same gradient to both the area and the context bar:

// set up gradient elements
var gradient = defs.append('linearGradient')
    .attr('id', 'spectrumGradient');

// set up gradient scale
var gx = d3.scale.linear().range([0, 1]);

Then, when the data is loaded, you create stop elements for each color:

// update gradient scale
gx.domain(x.domain());
// create gradient
gradient.selectAll('stop')
    // remove duplicates
    .data(data)
  .enter().append('stop')
    .attr('offset', function(d) { return gx(d.wl); })
    .attr('stop-color', toRGB); 

And apply it using url(#id) notation:

focus.append("path")
  .datum(data)
  .attr("clip-path", "url(#clip)")
  .attr("d", area)
  .attr('fill', 'url(#spectrumGradient)');
like image 181
nrabinowitz Avatar answered Oct 10 '22 04:10

nrabinowitz