Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Last active March 4, 2017 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timelyportfolio/6085852 to your computer and use it in GitHub Desktop.
Save timelyportfolio/6085852 to your computer and use it in GitHub Desktop.
Sankey of rCharts Example Gallery
require(rCharts)
require(plyr)
gallery <- read.csv(
"https://docs.google.com/spreadsheet/pub?key=0AovoNzJt5GetdEhQVDgyYXpJMnZ2M2J2YmtvX0I5Snc&output=csv",
stringsAsFactors = FALSE
)
gallery.use <- gallery[,c("technology","visualizationType","documentType","author")]
colnames(gallery.use) <- rep("column",4)
gallery.edge <- rbind(
gallery.use[,1:2],
gallery.use[,2:3],
gallery.use[,3:4],
deparse.level=1
)
colnames(gallery.edge) <- c("source","target")
gallery.edge <- ddply(gallery.edge,~source+target,nrow)
colnames(gallery.edge) <- c("source","target","value")
#verify that no source = target
#or will get stuck in infinite loop
gallery.edge[which(gallery.edge[,1]==gallery.edge[,2]),]
gallery.edge$source <- as.character(gallery.edge$source)
gallery.edge$target <- as.character(gallery.edge$target)
sankeyPlot2 <- rCharts$new()
sankeyPlot2$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey/')
sankeyPlot2$set(
data = gallery.edge,
nodeWidth = 15,
nodePadding = 10,
layout = 32,
width = 960,
height = 500
)
sankeyPlot2
<!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://twitter.github.io/bootstrap/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: 550px;
}
/*
body {
margin-top: 60px;
}
*/
</style>
</head>
<body>
<div class='container'>
<div class='row'>
<div class='span10'>
<div class="bs-docs-example">
<div id='chart2a2c51233980' class='rChart nvd3Plot rCharts_d3_sankey'></div>
<br/>
<pre><code class='r'>require(rCharts)
require(plyr)
gallery &lt;- read.csv(
&quot;https://docs.google.com/spreadsheet/pub?key=0AovoNzJt5GetdEhQVDgyYXpJMnZ2M2J2YmtvX0I5Snc&amp;output=csv&quot;,
stringsAsFactors = FALSE
)
gallery.use &lt;- gallery[,c(&quot;technology&quot;,&quot;visualizationType&quot;,&quot;documentType&quot;,&quot;author&quot;)]
colnames(gallery.use) &lt;- rep(&quot;column&quot;,4)
gallery.edge &lt;- rbind(
gallery.use[,1:2],
gallery.use[,2:3],
gallery.use[,3:4],
deparse.level=1
)
colnames(gallery.edge) &lt;- c(&quot;source&quot;,&quot;target&quot;)
gallery.edge &lt;- ddply(gallery.edge,~source+target,nrow)
colnames(gallery.edge) &lt;- c(&quot;source&quot;,&quot;target&quot;,&quot;value&quot;)
#verify that no source = target
#or will get stuck in infinite loop
gallery.edge[which(gallery.edge[,1]==gallery.edge[,2]),]
gallery.edge$source &lt;- as.character(gallery.edge$source)
gallery.edge$target &lt;- as.character(gallery.edge$target)
sankeyPlot2 &lt;- rCharts$new()
sankeyPlot2$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey/')
sankeyPlot2$set(
data = gallery.edge,
nodeWidth = 15,
nodePadding = 10,
layout = 32,
width = 960,
height = 500
)
sankeyPlot2
</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": "chart2a2c51233980",
"width": 960,
"height": 500,
"data": {
"source": [ "area", "bar chart", "block matrix", "blog post", "bump chart", "combination", "cumulative line", "custom", "d3", "d3", "d3", "dashboard", "dashifyr", "datatables", "dimple", "dimple", "dimple", "gallery", "highcharts", "highcharts", "highcharts", "highcharts", "leaflet", "line chart", "line chart", "map", "morris", "morris", "multiple", "multiple", "multiple", "multiple", "nvd3", "nvd3", "parallel coordinates", "parcoords", "polychart", "polychart", "rickshaw", "rickshaw", "sankey", "sankey", "sankey", "scatter", "scatter", "scatterplot", "shinyapp", "standalone visualization", "standalone visualization", "standalone visualization", "standalone visualization", "standalone visualization", "standalone visualization", "table", "timeline", "timelinejs", "tutorial", "tutorial" ],
"target": [ "standalone visualization", "standalone visualization", "standalone visualization", "TimelyPortfolio", "standalone visualization", "multiple", "tutorial", "standalone visualization", "cumulative line", "custom", "sankey", "shinyapp", "dashboard", "table", "block matrix", "multiple", "scatter", "TimelyPortfolio", "area", "bar chart", "line chart", "scatterplot", "map", "standalone visualization", "tutorial", "shinyapp", "line chart", "multiple", "gallery", "shinyapp", "standalone visualization", "tutorial", "bar chart", "scatterplot", "tutorial", "parallel coordinates", "multiple", "scatterplot", "bump chart", "multiple", "blog post", "standalone visualization", "tutorial", "standalone visualization", "tutorial", "standalone visualization", "Ramnath Vaidyanathan", "Alex Bresler", "Ian Dunham", "pssGuy", "Ramnath Vaidyanathan", "Thomas Reinholdsson", "TimelyPortfolio", "standalone visualization", "standalone visualization", "timeline", "Ramnath Vaidyanathan", "TimelyPortfolio" ],
"value": [ 2, 3, 1, 1, 1, 2, 1, 1, 1, 1, 5, 1, 1, 2, 1, 2, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 5, 2, 1, 1, 1, 4, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 2, 1, 2, 6, 2, 8, 2, 2, 2, 2, 8 ]
},
"nodeWidth": 15,
"nodePadding": 10,
"layout": 32,
"id": "chart2a2c51233980"
};
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