Bar Chart with baseline at center, rather than traditional top or bottom of the chart.
Last active
August 14, 2016 08:53
-
-
Save lsquaredleland/bdb97e2e53116ddc176f to your computer and use it in GitHub Desktop.
Bar Chart with baseline at center
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Bar Chart Base in Middle</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 margin = {top: 10, right: 10, bottom: 10, left: 10}; | |
var w = 700 - margin.left - margin.right; | |
h = 450 - margin.top - margin.bottom; | |
barPadding = 1; | |
var svg = d3.select("#chart").append("svg") | |
.attr({ | |
width: w + margin.left + margin.right, | |
height: h + margin.top + margin.bottom | |
}) | |
.append("g") | |
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); | |
var xScale = d3.scale.ordinal() | |
.domain(d3.range(dataSet1.length)) | |
.rangeRoundBands([0, w], 0.05); | |
var yScale = d3.scale.linear() | |
.domain([0, d3.max(dataSet1)]) | |
.range([0, h]); | |
function color(d){ return "rgb(150," + d * 10 + "," + d * 15 + ")"; }; | |
svg.selectAll("rect") | |
.data(dataSet1) | |
.enter() | |
.append("rect") | |
.attr({ | |
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); }, | |
fill: function(d){ return color(d); } | |
}); | |
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(dataSet1) | |
.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