tic
tic

Reputation: 4189

a compact way to code chained transitions in D3

I have to apply two long sequences of chained transitions which differ mainly in the order of transitions on some elements, and I'm looking for a compact way to code. Suppose (only as a toy example) that I have two circles and I have to apply the following colors to the first one:

orange -> purple -> blue -> yellow;

and the following colors to the second one:

blue -> yellow -> orange -> purple.

I've tried with the code below (fiddle here), but it doesn't work. Which is the most compact way to achieve this?

    var svg = d3.select('svg');

    var dataSet = [20, 20];

    var group=svg.append("g");
    var circles = group.selectAll('circle')
    .data(dataSet)
    .enter()
    .append('circle')
    .attr("r",function(d){ return d })
    .attr("cx",function(d, i){ return i * 100 + 50 })
    .attr("cy",50)
    .attr("fill",'black');

    var t1 = d3
    .transition()
    .duration(1000)
    .attr("fill","orange")
    .transition()
    .duration(1000)
    .attr("fill","purple");

    var t2 = d3
    .transition()
    .duration(1000)
    .attr("fill","blue")
    .transition()
    .duration(1000)
    .attr("fill","yellow");

    group.select(":nth-child(1)")
    .transition(t1).transition(t2); 
    group.select(":nth-child(2)")
    .transition(t2).transition(t1); 

Upvotes: 2

Views: 142

Answers (2)

Andrew Reid
Andrew Reid

Reputation: 38161

There are a multitude of ways to achieve this. As noted in the other answer, using a function for this will keep your code compact. Personally I tend to use the transition's end event to trigger the next transition from within the transition function.

The general form for this sort of function is as follows:

function transition() {
   // ....  optional logic here.
   d3.select(this) // do transition:
     .transition()
     .attr("fill", ... )
     .on("end", transition); // and repeat.
}

It can be called with selection.each(transition)

One approach to managing the current color/transition in the cycle is to use a custom attribute. Below I use .attr("i") to keep track:

var data = [
  ["orange","purple","blue","yellow"],
  ["blue","yellow","orange","purple"]
];

var svg = d3.select("svg");
var circles = svg.selectAll()
  .data(data)
  .enter()
  .append("circle")
  .attr("r", 20)
  .attr("cx", function(d,i) { return i * 50 + 50; })
  .attr("cy", 50)
  .attr("fill", function(d) { return d[0]; })
  .attr("i",0)
  .each(transition);


// cycle endlessly:
function transition() {
  var selection = d3.select(this);
  // keep track of current value:
  var i = selection.attr("i")
  selection
    .attr("i",i = ++i%4)
    .transition()  
    .duration(1000)
    .attr("fill", function(d) { return d[i] })
    .on("end", transition);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
<svg width="500" height="300"></svg>

If you have transitions that differ only in order (start point), you can modify the above approach a bit:

var data = [50,75,100,125,150,175,200,225];
var colors = ["orange","purple","blue","yellow"];

var svg = d3.select("svg");
var circles = svg.selectAll()
  .data(data)
  .enter()
  .append("circle")
  .attr("r", 20)
  .attr("cx", function(d) { return d; })
  .attr("cy", 50)
  .attr("fill", function(d,i) { return colors[i%4]; }) // set start fill
  .attr("i", function(d,i) { return i%4;  })   // record start position.
  .each(transition);

function transition() {
  var selection = d3.select(this);
  var i = selection.attr("i");
  i = ++i%colors.length;
  selection.transition()
      .duration(1000)
      .attr("i",i)
      .attr("fill", colors[i])
      .on("end", transition);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
<svg width="500" height="300"></svg>

First one I use color sets as the datum, second one I just use position accessing the color with the i attribute


The above methods use a custom attribute, but we can use the datum too. This allows us a bit more D3 familiarity in some ways.

For example, we can have a property called color and increment that while setting the fill on each transition (again assuming we have a colors array and each circle starts at a different point on it):

function transition() {
  d3.select(this).transition()
      .duration(1000)
      .attr("fill", function(d) { return colors[++d.color%colors.length]; })
      .on("end", transition);
}

var data = d3.range(8).map(function(d) { return {x: d*25+50}; })

var colors = ["orange","purple","blue","yellow"];

var svg = d3.select("svg");
var circles = svg.selectAll()
  .data(data)
  .enter()
  .append("circle")
  .attr("r", 20)
  .attr("cx", function(d) { return d.x; })
  .attr("cy", 50)
  .attr("fill", function(d,i) { return colors[i%4]; }) // set start fill
  .each(function(d,i) { d.color = i%4; })              // record start position.
  .each(transition);

function transition() {
  d3.select(this).transition()
      .duration(1000)
      .attr("fill", function(d) { return colors[++d.color%colors.length]; })
      .on("end", transition);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
<svg width="500" height="300"></svg>

If you want the transitions to repeat x times, or even have all end on the same color, we can do that fairly easily too by adding a new property to the datum to track cycles completed:

var data = d3.range(8).map(function(d) { return {x: d*25+50}; })

var colors = ["orange","purple","blue","yellow"];

var svg = d3.select("svg");
var circles = svg.selectAll()
  .data(data)
  .enter()
  .append("circle")
  .attr("r", 20)
  .attr("cx", function(d) { return d.x; })
  .attr("cy", 50)
  .attr("fill", function(d,i) { return colors[i%4]; }) // set start fill
  .each(function(d,i) { d.color = d.start = i%4; })              // record start position.
  .each(transition);
  
var n = 8; // n cycles

function transition() {
  d3.select(this).transition()
    .duration(1000)
    .attr("fill", function(d) { return colors[++d.color%colors.length]; })
    .on("end", function(d) { if(d.color - d.start < n) transition.apply(this); else return null; });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
<svg width="500" height="300"></svg>

There are lazier ways that destructively modify the datum (or portions of it), such as using shift in this transition cycle that can only run once:

var data = [
  ["orange","purple","blue","yellow"],
  ["blue","yellow","orange","purple"]
];

var svg = d3.select("svg");
var circles = svg.selectAll()
  .data(data)
  .enter()
  .append("circle")
  .attr("r", 20)
  .attr("cx", function(d,i) { return i * 50 + 50; })
  .attr("cy", 50)
  .attr("fill", function(d) { return d.shift(); })
  .each(transition);

function transition() {
  var selection = d3.select(this);
  if(selection.datum().length) {
    selection.transition()
      .duration(1000)
      .attr("fill", function(d) { return d.shift() })
      .on("end", transition);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
<svg width="500" height="300"></svg>

You might see that none of my snippets use child selectors: this can be avoided by custom attributes, datum properties, or more simply, using .attr("fill",function(d,i){ in the transition itself to differentiate odd and even elements. I have nothing against those selectors though, it just requires additional selections to be made.

Upvotes: 3

i alarmed alien
i alarmed alien

Reputation: 9520

If you create a function to apply the transition, you can compact your code down a fair bit:

/**
 * Apply a transition with the appropriate delay to a selection
 *
 * @param sel: a d3 selection
 * @param fill: the fill colour
 * @param position: the position of the colour in the set of transitions
 */

function tr(sel, fill, position) {
    sel.transition()
    .duration(1000)
    .delay(1000 * position)
    .ease(d3.easeLinear)
    .attr("fill", fill);
}

// example of use:
tr(group.select(":nth-child(1)"), 'blue', 0)
tr(group.select(":nth-child(2)"), 'red', 2)

In action:

function tr(sel, fill, pos) {
	sel.transition()
	.duration(1000)
    .delay(1000 * pos)
	.ease(d3.easeLinear)
	.attr("fill", fill);
}

var svg = d3.select('svg');

var dataSet = [20, 20];

var group = svg.append("g");
var circles = group.selectAll('circle')
    .data(dataSet)
    .enter()
    .append('circle')
    .attr("r",function(d){ return d })
    .attr("cx",function(d, i){ return i * 100 + 50 })
    .attr("cy",50)
    .attr("fill",'black');

var colors = {
  1: [ 'orange', 'purple', 'blue', 'yellow' ],
  2: [ 'deepskyblue', 'deeppink', 'goldenrod', 'magenta']
};

Object.keys(colors).forEach(function(ix){
   var el = group.select(":nth-child(" + ix + ")");
   colors[ix].forEach( function(c,i) { tr(el, c, i); });
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

Upvotes: 2

Related Questions