3

I have made a sankey diagram with rChars package in R.

But I want to add a function, when we move to a link or a target node, it will show all the names of source node in a tooltip (or a new box at the right top of the graph). For example, it will show "ddd.fr, pramana.fr" when we move to the node "target1".

I'm new in d3.js and know little about svg attribute. I have tried to do something with "link.append("title").text" or "node.append("title").text". But what I have done seem to be no use, because the function(d) always return one data but not an array.

Here is my code, hope someone can help, thanks !

<!doctype HTML>
<meta charset = 'utf-8'>
<html>
<head>
<link rel='stylesheet' href='http://timelyportfolio.github.io/rCharts_d3_sankey/css/sankey.css'>

<script src='http://timelyportfolio.github.io/rCharts_d3_sankey/js/d3.v3.js'     type='text/javascript'></script>
<script src='http://timelyportfolio.github.io/rCharts_d3_sankey/js/sankey.js' type='text/javascript'></script>

<style>
.rChart {
  display: block;
  margin-left: auto; 
  margin-right: auto;
  width: 900px;
  height: 1000px;
}  
</style>

</head>
<body >

<div id = 'chart202c4a213951' class = 'rChart rCharts_d3_sankey'></div>    
<!--Attribution:
Mike Bostock https://github.com/d3/d3-plugins/tree/master/sankey
Mike Bostock http://bost.ocks.org/mike/sankey/
-->

<script>
(function(){
var params = {
"dom": "chart202c4a213951",
"width":    800,
"height":   300,
"data": {
 "source": [ "A.fr", "B.fr", "C.fr", "ddd.fr", "pramana.fr", "pramana.fr" ],
"target": [ "pramana.fr", "pramana.fr", "ddd.fr", "target1", "target1", "target2" ],
"cat": [    0,  1,     0,      1,     0,      -1 ] ,
"value": [    1,  1,     1,      1,     1,     1] 
},
"nodeWidth":     15,
"nodePadding":     10,
"layout":     32,
"units": "freq",
"title": "Sankey Diagram pramana",
"id": "chart202c4a213951" 
};

params.units ? units = " " + params.units : units = "";

//hard code these now but eventually make available
var formatNumber = d3.format("0,.0f"),    // zero decimal places
format = function(d) { return formatNumber(d) + units; },
color = d3.scale.category20();

if(params.labelFormat){
  formatNumber = d3.format(".2%");
}

var svg = d3.select('#' + params.id).append("svg")
.attr("width", params.width)
.attr("height", params.height);

var sankey = d3.sankey()
.nodeWidth(params.nodeWidth)
.nodePadding(params.nodePadding)
.layout(params.layout)
.size([params.width,params.height]);

var path = sankey.link();

var data = params.data,
links = [],
nodes = [];

//get all source and target into nodes
//will reduce to unique in the next step
//also get links in object form
data.source.forEach(function (d, i) {
nodes.push({ "name": data.source[i] });
nodes.push({ "name": data.target[i] });
links.push({ "source": data.source[i], "target": data.target[i], "value": +data.value[i] });
}); 

//now get nodes based on links data
//thanks Mike Bostock https://groups.google.com/d/msg/d3-js/pl297cFtIQk/Eso4q_eBu1IJ
//this handy little function returns only the distinct / unique nodes
nodes = d3.keys(d3.nest()
            .key(function (d) { return d.name; })
            .map(nodes));

//it appears d3 with force layout wants a numeric source and target
//so loop through each link replacing the text with its index from node
links.forEach(function (d, i) {
links[i].source = nodes.indexOf(links[i].source);
links[i].target = nodes.indexOf(links[i].target);
});

//now loop through each nodes to make nodes an array of objects rather than an array of strings
nodes.forEach(function (d, i) {
nodes[i] = { "name": d };
});

sankey
  .nodes(nodes)
  .links(links)
  .layout(params.layout);

var link = svg.append("g").selectAll(".link")
  .data(links)
  .enter().append("path")
  .attr("class", "link")
  .attr("d", path)
  .style("stroke-width", function (d) { return Math.max(1, d.dy); })
  .sort(function (a, b) { return b.dy - a.dy; });

link.append("title")
  .text(function (d) { return d.source.name + " → " + d.target.name + "\n" + format(d.value); });

var node = svg.append("g").selectAll(".node")
  .data(nodes)
.enter().append("g")
  .attr("class", "node")
  .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
  .origin(function (d) { return d; })
  .on("dragstart", function () { this.parentNode.appendChild(this); })
  .on("drag", dragmove));

node.append("rect")
  .attr("height", function (d) { return d.dy; })
  .attr("width", sankey.nodeWidth())
  .style("fill", function (d) { return d.color = color(d.name.replace(/ .*/, "")); })
  .style("stroke", function (d) { return d3.rgb(d.color).darker(2); })
.append("title")
  .text(function (d) { return d.name + "\n" + format(d.value); });

node.append("text")
  .attr("x", -6)
  .attr("y", function (d) { return d.dy / 2; })
  .attr("dy", ".35em")
  .attr("text-anchor", "end")
  .attr("transform", null)
  .text(function (d) { return d.name; })
.filter(function (d) { return d.x < params.width / 2; })
  .attr("x", 6 + sankey.nodeWidth())
  .attr("text-anchor", "start");

// the function for moving the nodes
  function dragmove(d) {
d3.select(this).attr("transform", 
    "translate(" + (
               d.x = Math.max(0, Math.min(params.width - d.dx, d3.event.x))
            ) + "," + (
               d.y = Math.max(0, Math.min(params.height - d.dy, d3.event.y))
            ) + ")");
    sankey.relayout();
    link.attr("d", path);
  }
})();

</script>

  </body>
</html>
Estelle Zhang
  • 33
  • 1
  • 3

1 Answers1

2

In your function that is supposed to retrieve names of other nodes that are "source" (or"target", implementation would be the same) to the current node, you can do something like this:

function(d,i){
        d.sourceLinks.forEach(function(srcLnk){
            // find the name of the other end of the link
        });
        d.targetLinks.forEach(function(tgtLnk){
            // find the name of the other end of the link
        });
}

In other words, use d.sourceLinks and d.targetLinks. And you gradually add names one by one, and display wherever you find suitable (tooltip, separate box, etc.).

In turn, each link has property source and target, and you can use something like srcLnk.source.name to obtain the name of one of the nodes that is a "source" for the current node.

I am writing this by hearth, so double check everything, some properties may have differeent name than I said.

Hope this helps.


UPDATE: jsfiddle

enter image description here

Key code:

.append("title")
.text(function (d) {
    var titleText = d.name + " - " +
        format(d.value) + " total" + "\n" + "\n";
    var sourcesText = "";  
    d.targetLinks.forEach(function(dstLnk){
        sourcesText += "from " + dstLnk.source.name + " - " +
            format(dstLnk.value) + "\n";
    });
    return titleText + sourcesText;
});
VividD
  • 10,456
  • 6
  • 64
  • 111
  • Thanks so much!!! This is exactly what I want! This is very helpful for me to know this usage, but can you explain more how to implement in the code ? I have tried like .append("title").text(function (d,i){...}. – Estelle Zhang Jan 11 '15 at 15:47
  • By the way, I see there are many kinds of tooltip, how to add a tooltip in this sankey.js ? (Sorry, I learned it just a few days, really new to this) – Estelle Zhang Jan 11 '15 at 15:59
  • For some reason I couldn't use your code, but I put together another example. See also the code snippet below the pic. Adjust that code to your needs.@EstelleZhang – VividD Jan 11 '15 at 17:41
  • Really nice to have such a perfect explanation! It works now! Just one more question, do you think it's the same thing/idea in highlighting all connected path (maybe a properties with one line's code in the same place) ? or is it more complicated (write a function/algorithm "traverse") ? – Estelle Zhang Jan 11 '15 at 18:50