Skip to content

Instantly share code, notes, and snippets.

@jmcmurry
Created February 20, 2018 18:56
Show Gist options
  • Save jmcmurry/bfca5f41fea1bd1fad3a274964acaf5a to your computer and use it in GitHub Desktop.
Save jmcmurry/bfca5f41fea1bd1fad3a274964acaf5a to your computer and use it in GitHub Desktop.
Sankey Plot of Grant Funding
license: mit
grant_id <- 1:100
funding_agency <- sample(rep(c("NIAID", "NIGMS", "NHLBI", "NCI", "NINDS"), 20))
study_section <- sample(rep(
c("Tumor Cell Biology", "Tumor Progression", "Vector Biology",
"Molecular Genetics", "Medical Imaging", "Macromolecular Structure",
"Infectious Diseases", "Drug Discovery",
"Cognitive Neuroscience", "Aging and Geriatrics"), 10
))
total_cost <- rnorm(100, mean = 30000, sd = 10000)
# source, target and value have to be the names
d <- data.frame(
id = grant_id,
source = funding_agency,
target = study_section,
value = total_cost
)
require(rCharts)
sankeyPlot <- rCharts$new()
sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey')
sankeyPlot$set(
data = d,
nodeWidth = 15,
nodePadding = 10,
layout = 32,
width = 750,
height = 500,
labelFormat = ".1%"
)
sankeyPlot
<!doctype HTML>
<meta charset = 'utf-8'>
<html>
<head>
<link rel='stylesheet' href="http://netdna.bootstrapcdn.com/bootswatch/2.3.1/cosmo/bootstrap.min.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-responsive.min.css" >
<link rel='stylesheet' href="http://getbootstrap.com/2.3.2/assets/js/google-code-prettify/prettify.css">
<link rel='stylesheet' href="http://aozora.github.io/bootplus/assets/css/docs.css">
<link rel='stylesheet' href='http://timelyportfolio.github.io/rCharts_d3_sankey/css/sankey.css'>
<script src='http://d3js.org/d3.v3.min.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: auto auto;
width: 100%;
height: 500px;
}
/*
body {
margin-top: 60px;
}
*/
</style>
</head>
<body>
<div class='container'>
<div class='row'>
<div class='span8'>
<div class="bs-docs-example">
<div id='chart4052b382652' class='rChart rCharts_d3_sankey'>
</div>
<br/>
<pre><code class='r'>grant_id &lt;- 1:100
funding_agency &lt;- sample(rep(c(&quot;NIAID&quot;, &quot;NIGMS&quot;, &quot;NHLBI&quot;, &quot;NCI&quot;, &quot;NINDS&quot;), 20))
study_section &lt;- sample(rep(
c(&quot;Tumor Cell Biology&quot;, &quot;Tumor Progression&quot;, &quot;Vector Biology&quot;,
&quot;Molecular Genetics&quot;, &quot;Medical Imaging&quot;, &quot;Macromolecular Structure&quot;,
&quot;Infectious Diseases&quot;, &quot;Drug Discovery&quot;,
&quot;Cognitive Neuroscience&quot;, &quot;Aging and Geriatrics&quot;), 10
))
total_cost &lt;- rnorm(100, mean = 30000, sd = 10000)
# source, target and value have to be the names
d &lt;- data.frame(
id = grant_id,
source = funding_agency,
target = study_section,
value = total_cost
)
require(rCharts)
sankeyPlot &lt;- rCharts$new()
sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey')
sankeyPlot$set(
data = d,
nodeWidth = 15,
nodePadding = 10,
layout = 32,
width = 750,
height = 500,
labelFormat = &quot;.1%&quot;
)
sankeyPlot
</code></pre>
</div>
</div>
</div>
</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": "chart4052b382652",
"width": 600,
"height": 500,
"data": {
"id": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 ],
"source": [ "NHLBI", "NIGMS", "NINDS", "NIAID", "NCI", "NIGMS", "NIGMS", "NHLBI", "NINDS", "NIGMS", "NINDS", "NHLBI", "NINDS", "NINDS", "NIAID", "NIAID", "NINDS", "NHLBI", "NHLBI", "NINDS", "NIGMS", "NHLBI", "NIGMS", "NCI", "NINDS", "NIAID", "NINDS", "NIAID", "NCI", "NIAID", "NCI", "NHLBI", "NINDS", "NINDS", "NIGMS", "NHLBI", "NHLBI", "NIGMS", "NIAID", "NCI", "NINDS", "NIAID", "NCI", "NINDS", "NINDS", "NCI", "NINDS", "NIGMS", "NIAID", "NHLBI", "NCI", "NHLBI", "NCI", "NIGMS", "NHLBI", "NIGMS", "NIAID", "NIGMS", "NIGMS", "NIGMS", "NHLBI", "NIAID", "NCI", "NIAID", "NCI", "NIAID", "NIAID", "NINDS", "NCI", "NCI", "NCI", "NHLBI", "NCI", "NHLBI", "NINDS", "NCI", "NIAID", "NIGMS", "NIGMS", "NIAID", "NIAID", "NIAID", "NHLBI", "NCI", "NIAID", "NHLBI", "NINDS", "NHLBI", "NIAID", "NCI", "NINDS", "NIGMS", "NHLBI", "NIGMS", "NCI", "NINDS", "NIGMS", "NCI", "NHLBI", "NIGMS" ],
"target": [ "Tumor Progression", "Medical Imaging", "Tumor Cell Biology", "Tumor Progression", "Molecular Genetics", "Vector Biology", "Drug Discovery", "Tumor Cell Biology", "Tumor Progression", "Vector Biology", "Drug Discovery", "Molecular Genetics", "Cognitive Neuroscience", "Aging and Geriatrics", "Drug Discovery", "Macromolecular Structure", "Cognitive Neuroscience", "Tumor Progression", "Tumor Progression", "Drug Discovery", "Aging and Geriatrics", "Macromolecular Structure", "Tumor Cell Biology", "Aging and Geriatrics", "Infectious Diseases", "Molecular Genetics", "Molecular Genetics", "Vector Biology", "Drug Discovery", "Vector Biology", "Infectious Diseases", "Cognitive Neuroscience", "Tumor Cell Biology", "Infectious Diseases", "Infectious Diseases", "Medical Imaging", "Tumor Cell Biology", "Macromolecular Structure", "Molecular Genetics", "Aging and Geriatrics", "Tumor Cell Biology", "Infectious Diseases", "Molecular Genetics", "Medical Imaging", "Macromolecular Structure", "Medical Imaging", "Medical Imaging", "Vector Biology", "Medical Imaging", "Infectious Diseases", "Vector Biology", "Infectious Diseases", "Vector Biology", "Drug Discovery", "Tumor Progression", "Infectious Diseases", "Cognitive Neuroscience", "Cognitive Neuroscience", "Tumor Progression", "Macromolecular Structure", "Aging and Geriatrics", "Medical Imaging", "Cognitive Neuroscience", "Molecular Genetics", "Cognitive Neuroscience", "Vector Biology", "Molecular Genetics", "Aging and Geriatrics", "Vector Biology", "Drug Discovery", "Tumor Progression", "Tumor Cell Biology", "Drug Discovery", "Macromolecular Structure", "Molecular Genetics", "Tumor Cell Biology", "Vector Biology", "Tumor Progression", "Macromolecular Structure", "Aging and Geriatrics", "Aging and Geriatrics", "Drug Discovery", "Medical Imaging", "Tumor Cell Biology", "Infectious Diseases", "Cognitive Neuroscience", "Tumor Cell Biology", "Molecular Genetics", "Cognitive Neuroscience", "Medical Imaging", "Medical Imaging", "Macromolecular Structure", "Infectious Diseases", "Drug Discovery", "Cognitive Neuroscience", "Aging and Geriatrics", "Macromolecular Structure", "Aging and Geriatrics", "Tumor Progression", "Macromolecular Structure" ],
"value": [ 39248, 24965, 31923, 21533, 25620, 41433, 33301, 21045, 37890, 27784, 18994, 14374, 30338, 15981, 23806, 38275, 38542, 28493, 44187, 48459, 11917, 13955, 36743, 44311, 38981, 37216, 36440, 33003, 30409, 37891, 36054, 13075, 22739, -1183.8, 24874, 26118, 9745.8, 27882, 42256, 23189, 17810, 35074, 56706, 33450, 33632, 23870, 33459, 45018, 18730, 25134, 15530, 20649, 15730, 42701, 25808, 30076, 36254, 24095, 42341, 34360, 29840, 15335, 39168, 15820, 27226, 31207, 33662, 32191, 16266, 10977, 22212, 38767, 36056, 33025, 12022, 14788, 25265, 39209, 30252, 41617, 42562, 37682, 28336, 40039, 29221, 23372, 51020, 29624, 51238, 28877, 21952, 32644, 24850, 36817, 23121, 15700, 37714, 37087, 31037, 41261 ]
},
"nodeWidth": 15,
"nodePadding": 10,
"layout": 32,
"labelFormat": ".1%",
"id": "chart4052b382652"
};
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>
<!-- Google Prettify -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/prettify/188.0.0/prettify.js"></script>
<script
src='https://google-code-prettify.googlecode.com/svn-history/r232/trunk/src/lang-r.js'>
</script>
<script>
var pres = document.getElementsByTagName("pre");
for (var i=0; i < pres.length; ++i) {
pres[i].className = "prettyprint linenums";
}
prettyPrint();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment