Skip to content

Instantly share code, notes, and snippets.

@edharmowongso
Created May 29, 2017 16:34
Show Gist options
  • Save edharmowongso/004391aab00ff83da2c0781ff30a2626 to your computer and use it in GitHub Desktop.
Save edharmowongso/004391aab00ff83da2c0781ff30a2626 to your computer and use it in GitHub Desktop.
Diverging Stacked Bar Chart
license: mit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Diverging Stacked Bar Chart with D3.js</title>
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3.min.js"></script>
<body>
<div><button onclick="prepareDownload();">prepareDownload</button><a id="link" href="">download</a> </div>
<div id="figure" style="margin-bottom: 50px;"></div>
<script>
var margin = {top: 50, right: 20, bottom: 10, left: 65},
width = 800 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.rangeRoundBands([0, height], .3);
var x = d3.scale.linear()
.rangeRound([0, width]);
var color = d3.scale.ordinal()
.range(["#c7001e", "#f6a580", "#cccccc", "#92c6db", "#086fad"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("top");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
var svg = d3.select("#figure").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("id", "d3-plot")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
color.domain(["Strongly disagree", "Disagree", "Neither agree nor disagree", "Agree", "Strongly agree"]);
d3.csv("raw_data.csv", function(error, data) {
data.forEach(function(d) {
// calc percentages
d["Strongly disagree"] = +d[1]*100/d.N;
d["Disagree"] = +d[2]*100/d.N;
d["Neither agree nor disagree"] = +d[3]*100/d.N;
d["Agree"] = +d[4]*100/d.N;
d["Strongly agree"] = +d[5]*100/d.N;
var x0 = -1*(d["Neither agree nor disagree"]/2+d["Disagree"]+d["Strongly disagree"]);
var idx = 0;
d.boxes = color.domain().map(function(name) { return {name: name, x0: x0, x1: x0 += +d[name], N: +d.N, n: +d[idx += 1]}; });
});
var min_val = d3.min(data, function(d) {
return d.boxes["0"].x0;
});
var max_val = d3.max(data, function(d) {
return d.boxes["4"].x1;
});
x.domain([min_val, max_val]).nice();
y.domain(data.map(function(d) { return (d.Question); }));
svg.append("g")
.attr("class", "x axis")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
var vakken = svg.selectAll(".question")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(0," + y(d.Question) + ")"; });
var bars = vakken.selectAll("rect")
.data(function(d) { return d.boxes; })
.enter().append("g").attr("class", "subbar");
bars.append("rect")
.attr("height", 20) //y.rangeBand()
.attr("x", function(d) { return x(d.x0); })
.attr("width", function(d) { return x(d.x1) - x(d.x0); })
.style("fill", function(d) { return color(d.name); });
bars.append("text")
.attr("x", function(d) { return x(d.x0); })
.attr("y", 10)//y.rangeBand()/2
.attr("dy", "0.5em")
.attr("dx", "0.5em")
.style("font" ,"10px sans-serif")
.style("text-anchor", "begin")
.style("color", function(d) { if (d.n<2) {return "000";} else {return "black";} })
.text(function(d) { return d.n !== 0 && (d.x1-d.x0)>3 ? d.n : "" });
vakken.insert("rect",":first-child")
.attr("height", 20)//y.rangeBand()
.attr("x", "1")
.attr("width", width)
.attr("fill-opacity", "0.5")
.style("fill", "#F5F5F5")
.attr("class", function(d,index) { return index%2==0 ? "even" : "uneven"; });
svg.append("g")
.attr("class", "y axis")
.append("line")
.attr("x1", x(0))
.attr("x2", x(0))
.attr("y2", height);
var startp = svg.append("g").attr("class", "legendbox").attr("id", "mylegendbox");
// this is not nice, we should calculate the bounding box and use that
var legend_tabs = [0, 120, 200, 375, 450];
var legend = startp.selectAll(".legend")
.data(color.domain().slice())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(" + legend_tabs[i] + ",-45)"; });
legend.append("rect")
.attr("x", 0)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", 22)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "begin")
.style("font" ,"10px sans-serif")
.text(function(d) { return d; });
d3.selectAll(".axis path")
.style("fill", "none")
.style("stroke", "#000")
.style("shape-rendering", "crispEdges")
d3.selectAll(".axis line")
.style("fill", "none")
.style("stroke", "#000")
.style("shape-rendering", "crispEdges")
var movesize = width/2 - startp.node().getBBox().width/2;
d3.selectAll(".legendbox").attr("transform", "translate(" + movesize + ",0)");
});
function prepareDownload() {
//get svg element.
var svgelt = document.getElementById("d3-plot");
//get svg source.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svgelt);
//add name spaces.
if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}
//add xml declaration
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
//convert svg source to URI data scheme.
var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source);
//set url value to a element's href attribute.
document.getElementById("link").href = url;
//you can download svg file by right click menu.
}
</script>
</body>
</html>
Question 1 2 3 4 5 N
comprehension_critere_indiciel 0 2 5 6 2 16
comprehension_critere_symbolique 3 3 6 2 2 16
comprehension_lien_indiciel 0 4 4 6 2 16
comprehension_lien_symbolique 0 3 6 4 3 16
comprehension_progression_indiciel 2 4 4 6 0 16
comprehension_progression_symbolique 2 5 5 4 0 16
comprehension_blocage_indiciel 1 2 5 8 0 16
comprehension_blocage_symbolique 3 3 6 3 1 16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment