Edu
Edu

Reputation: 107

D3.js Sankey diagram: Add title (text) above each column of nodes

I want to add titles above each column of nodes in a D3.js Sankey diagram. For example, I take this example: http://bl.ocks.org/d3noob/5028304 and this is the result I want:

Sankey graph

I thought something like this but it doesn't convince me. I'm looking for other alternatives.

        var columnNames=["step 1","step 2","step 3","step 4"];
        var distance=width/(columnNames.length-1);
        var pos=0;
        
        for (var i = 0; i < columnNames.length; i++){
            svg.append("text")
              .attr("x", pos)
              .text(columnNames[i]); 

            pos=pos+distance;
        }

How can I do that?

Thank you in advance.

Upvotes: 3

Views: 1072

Answers (2)

smcs
smcs

Reputation: 2004

Something like this, I'm sure there are cleaner solutions possible but it should work if you adapt the filters on x and y position for your case:

// add column titles left
node.append("text")
  .filter(function(d) {return d.y < 10})
    .filter(function(d) {return d.x < 10})
      .text("Left text")
      .style("font", "20px sans-serif")
      .attr("y", -20)
      .attr("x", -95)

// add column titles right
node.append("text")
  .filter(function(d) {return d.y < 10})
    .filter(function(d) {return d.x > 50})
      .text("Right text")
      .style("font", "20px sans-serif")
      .attr("y", -20)
      .attr("x", -50)

Upvotes: 0

Tom Shanley
Tom Shanley

Reputation: 1787

When the sankey is generated, each node in your sankey is assigned a dx value, which relates its position from the left. If you iterate through your nodes (graph.nodes), and create an array containing the unique dx values, you will know how many steps there are, and the x coordinate of the step label.

This array could be used as a data join to generate the labels, and the text could then be created using the value, eg label.text(function(d) { return "step " + d; })

Upvotes: 1

Related Questions