Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Last active December 20, 2016 19:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save timelyportfolio/79350d7475a5709b051e to your computer and use it in GitHub Desktop.
Save timelyportfolio/79350d7475a5709b051e to your computer and use it in GitHub Desktop.
color your d3 sankey using rCharts

How To Color Your d3.js Sankey Diagram

in this case with rCharts but relevant even without

In response to this Stack Overflow question Adding Color to Sankey Diagram in rCharts, I put this quick example together to demonstrate one way of handling.

demo

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$setTemplate(
afterScript = "
<script>
// to be specific in case you have more than one chart
d3.selectAll('#{{ chartId }} svg path.link')
.style('stroke', function(d){
//here we will use the source color
//if you want target then sub target for source
//or if you want something other than gray
//supply a constant
//or use a categorical scale or gradient
return d.source.color;
})
//note no changes were made to opacity
//to do uncomment below but will affect mouseover
//so will need to define mouseover and mouseout
//happy to show how to do this also
// .style('stroke-opacity', .7)
</script>
")
sankeyPlot2
<!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: 960px;
height: 500px;
}
</style>
</head>
<body >
<div id = 'chart21541f297cdc' 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": "chart21541f297cdc",
"width": 960,
"height": 500,
"data": {
"source": [ "area", "bar chart", "bar chart", "block matrix", "blog post", "blog post", "bump chart", "cal-heatmap", "calendar heatmap", "choropleth map", "combination", "combination", "correlation matrix", "cumulative line", "custom", "d3", "d3", "d3", "d3", "d3", "dashboard", "dashifyr", "datamaps", "datatables", "dimple", "dimple", "dimple", "dimple", "dimple", "dygraphs", "error bar", "gallery", "gallery", "heat map", "highcharts", "highcharts", "highcharts", "highcharts", "horizon", "horizon", "leaflet", "line chart", "line chart", "line chart", "map", "morris", "morris", "multiple", "multiple", "multiple", "multiple", "nvd3", "nvd3", "nvd3", "parallel coordinates", "parallel coordinates", "parcoords", "polychart", "polychart", "polychart", "polychart", "rickshaw", "rickshaw", "sankey", "sankey", "sankey", "scatter", "scatter", "scatterplot", "shinyapp", "standalone visualization", "standalone visualization", "standalone visualization", "standalone visualization", "standalone visualization", "standalone visualization", "standalone visualization", "table", "timeline", "timelinejs", "tutorial", "tutorial" ],
"target": [ "standalone visualization", "blog post", "standalone visualization", "standalone visualization", "Kyle Walker", "TimelyPortfolio", "standalone visualization", "calendar heatmap", "standalone visualization", "standalone visualization", "multiple", "scatterplot", "standalone visualization", "tutorial", "standalone visualization", "cumulative line", "custom", "error bar", "horizon", "sankey", "shinyapp", "dashboard", "choropleth map", "table", "bar chart", "block matrix", "multiple", "scatter", "scatterplot", "line chart", "standalone visualization", "TimelyPortfolio", "Vivek Patil", "standalone visualization", "area", "bar chart", "line chart", "scatterplot", "standalone visualization", "tutorial", "map", "blog post", "standalone visualization", "tutorial", "shinyapp", "line chart", "multiple", "gallery", "shinyapp", "standalone visualization", "tutorial", "bar chart", "line chart", "scatterplot", "standalone visualization", "tutorial", "parallel coordinates", "correlation matrix", "heat map", "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", "Vivek Patil", "standalone visualization", "standalone visualization", "timeline", "Ramnath Vaidyanathan", "TimelyPortfolio" ],
"value": [ 2, 2, 5, 1, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 5, 1, 1, 1, 4, 4, 1, 3, 2, 1, 2, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 4, 1, 1, 5, 2, 1, 1, 1, 1, 2, 1, 1, 4, 1, 1, 1, 1, 3, 1, 1, 1, 5, 3, 2, 1, 2, 8, 2, 15, 6, 4, 2, 2, 2, 9 ]
},
"nodeWidth": 15,
"nodePadding": 10,
"layout": 32,
"id": "chart21541f297cdc"
};
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>
<script>
// to be specific in case you have more than one chart
d3.selectAll('#chart21541f297cdc svg path.link')
.style('stroke', function(d){
//here we will use the source color
//if you want target then sub target for source
//or if you want something other than gray
//supply a constant
//or use a categorical scale or gradient
return d.source.color;
})
//note no changes were made to opacity
//to do uncomment below but will affect mouseover
//so will need to define mouseover and mouseout
//happy to show how to do this also
// .style('stroke-opacity', .7)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment