C2Task2ToySankey

by Simon Raper

HTML

<script src="http://bost.ocks.org/mike/sankey/sankey.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js"></script>
<div id="container"></div>

CSS

#chart {
    height: 500px;
}
.node rect {
    cursor: move;
    fill-opacity: .9;
    shape-rendering: crispEdges;
}
.node text {
    font-family:"raleway"
}
.link {
    fill: none;
    stroke: #000;
    stroke-opacity: .2;
}
.link:hover {
    stroke-opacity: .5;
}

JavaScript

var customer_journey = {
    "nodes": [{
        "name": "registration"
    }, {
        "name": "trial"
    }, {
        "name": "subscription"
    }, {
        "name": "pay as you go"
    }],
        "links": [{
        "source": 0,
            "target": 1,
            "value": 20
    }, {
        "source": 0,
            "target": 2,
            "value": 30
    }, {
        "source": 0,
            "target": 3,
            "value": 22
    }, {
        "source": 1,
            "target": 2,
            "value": 5
    }, {
        "source": 1,
            "target": 3,
            "value": 5
    }, {
        "source": 3,
            "target": 2,
            "value": 15
    }]
}


var margin = {
    top: 50,
    right: 1,
    bottom: 50,
    left: 50
},
width = 600 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;


var svg = d3.select("#container").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

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

var path = sankey.link();

sankey.nodes(customer_journey.nodes)
    .links(customer_journey.links)
    .layout(32);

var link = svg.append("g").selectAll(".link")
    .data(customer_journey.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" + d.value;
});

var node = svg.append("g").selectAll(".node")
    .data(customer_journey.nodes)
    .enter().append("g")
    .attr("class", "node")
    .attr("transform", function (d) {
    return "translate(" + d.x + "," + d.y + ")";
});

node.append("rect")
    .attr("height", function...