Skip to content

Instantly share code, notes, and snippets.

@alteist
Last active June 11, 2018 14:55
Show Gist options
  • Save alteist/cd0e3519d8078a10bc636619097665d5 to your computer and use it in GitHub Desktop.
Save alteist/cd0e3519d8078a10bc636619097665d5 to your computer and use it in GitHub Desktop.
bars of bars
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0;
background-color: #ccc
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<script>
var data =[[2011,0.11],[2012,0.44],[2013,-0.34],[2014,.24]]
// var width = 200
// var height = 200
var margin = {top: 20, right: 20, bottom: 64, left: 40}
var width = 313 - margin.left - margin.right
var height = 217 - margin.top - margin.bottom
var bar = {height: 10}
var svg = d3.select("body").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 x = d3.scaleBand().rangeRound([0, width], .05).padding(0.4);
var y = d3.scaleLinear().range([height, 0]);
data.forEach(function(d) {
d.date = d3.timeParse("%Y")(d[0]);
d.value = +d[1];
});
x.domain(data.map(function(d) { return d.date; }));
y.domain(d3.extent(data.map(function(d) { return d.value; })))
var xAxis = d3.axisBottom()
.scale(x)
.tickFormat(d3.timeFormat("%Y"))
var yAxis = d3.axisLeft()
.scale(y)
.ticks(4);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
svg.append("line")
.attr("y1",y(0))
.attr("y2",y(0))
.attr("x2",width)
.style("stroke","grey")
.style("stroke-width","0.5")
var bh = 4;
svg.selectAll("bar")
.data(data)
.enter()
.each(function (d, i) {
var g = d3.select(this)
.append("g")
.attr("class", function(d) { return "bar bar-" + (d.value < 0 ? "negative" : "positive"); })
var h = Math.abs(y(d.value) - y(0))
d3.range(0,Math.floor(h/bh/2)).forEach((p,j)=>{
// console.log(d.value)
if (d.value > 0) {
j=(j*-1)-0.5
g.append("rect")
.style("fill", "steelblue")
.attr("x", x(d.date))
.attr("width", x.bandwidth())
.attr("y", y(0) + j*bh*2 )
.attr("height", bh);
} else if (d.value < 0) {
g.append("rect")
.style("fill", "steelblue")
.attr("x", x(d.date))
.attr("width", x.bandwidth())
.attr("y", y(Math.max(0, d.value)) + j*bh*2 )
.attr("height", bh); }
})
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment