Skip to content

Instantly share code, notes, and snippets.

@lsquaredleland
Last active August 14, 2016 08:54
Show Gist options
  • Save lsquaredleland/a13cc48d088f19bb17b5 to your computer and use it in GitHub Desktop.
Save lsquaredleland/a13cc48d088f19bb17b5 to your computer and use it in GitHub Desktop.
2 Level Diverging Bar Chart - 2 DataSets Implimentation

2 Level Diverging Bar Chart, can use 2 different datasets or one (code must be modified). Note how in this version elements are not appended.

<!-- uses "classes" version of implimentation -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>2 Level Diverging Bar Chart - 2 DataSets Implimentation</title>
<script src="https://d3js.org/d3.v3.min.js"></script>
</head>
<style type="text/css">
#chart {
border: 2px dashed black;
}
/*styling of the text here instead of text.attr */
text {
font-family: sans-serif;
font-size: 11px;
fill: black;
text-anchor: middle;
}
</style>
<body>
<div id="chart"></div>
<script>
var dataSet1 = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25, 10, 13, 16, 5, 2 ];
var dataSet2 = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25, 10, 13, 16, 5, 2 ];
var w = 700;
h = 450;
barPadding = 1;
var svg = d3.select("#chart").append("svg")
.attr({
width: w,
height: h
});
var xScale = d3.scale.ordinal()
.domain(d3.range(dataSet1.length))
.rangeRoundBands([0, w], 0.05);//calculate even bands + add spacing
var maxDomain = d3.max(dataSet1) / 2 + d3.max(dataSet2) / 2;
var yScale = d3.scale.linear()
.domain([0, maxDomain])
.range([0, h]);
function color(d){ return "rgb(150," + d * 10 + "," + d * 15 + ")"; };
svg.selectAll("rect.valueTop")
.data(dataSet1)
.enter()
.append("rect")
.attr({
"class": "valueTop",
x: function(d, i) { return xScale(i); },
y: function(d) { return h - yScale(d)/2 - h/2; },
width: xScale.rangeBand(),
height: function(d){ return yScale(d) / 2; },
fill: function(d){ return color(d); }
});
svg.selectAll("rect.valueBottom")
.data(dataSet2)
.enter()
.append("rect")
.attr({
"class": "valueBottom",
x: function(d, i) { return xScale(i); },
y: function(d) { return h/2; },
width: xScale.rangeBand(),
height: function(d){ return yScale(d) / 2; },
fill: function(d){ return "red"; }
});
svg.selectAll("text.valueTop") // top
.data(dataSet1)
.enter()
.append("text")
.text(function(d) { return d; })
.attr({
"class": "valueTop",
x: function(d,i) { return xScale(i) + xScale.rangeBand() / 2 },
y: function(d) { return h - yScale(d)/2 - h/2 + 14; },
});
svg.selectAll("text.valueBottom") //bottom
.data(dataSet2)
.enter()
.append("text")
.text(function(d) { return d; })
.attr({
"class": "valueBottom",
x: function(d,i) { return xScale(i) + xScale.rangeBand() / 2 },
y: function(d) { return h + yScale(d)/2 - h/2 - 7; },
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment