Skip to content

Instantly share code, notes, and snippets.

@ericcoopey
Last active December 21, 2015 23:49
Show Gist options
  • Save ericcoopey/6384917 to your computer and use it in GitHub Desktop.
Save ericcoopey/6384917 to your computer and use it in GitHub Desktop.
D3 Binary Sparkline

Binary (up/down) sparkline in D3

Simple but cool

{"edges":[{"name":"Bob","top":"1","mine":"1"},{"name":"Ben ","top":"1","mine":"0"},{"name":"Ben ","top":"1","mine":"0"},{"name":"Ben ","top":"1","mine":"0"},{"name":"Sally","top":"0","mine":"0"},{"name":"Johnathon","top":"1","mine":"1"},{"name":"Bob","top":"0","mine":"1"},{"name":"Sally","top":"1","mine":"0"},{"name":"Bob","top":"1","mine":"1"},{"name":"Ben ","top":"1","mine":"0"},{"name":"Eric ","top":"1","mine":"0"},{"name":"Sally","top":"0","mine":"0"},{"name":"Ben ","top":"0","mine":"0"},{"name":"Bob ","top":"0","mine":"1"},{"name":"Susan","top":"1","mine":"0"}]}
<!DOCTYPE html>
<html>
<script src="http://d3js.org/d3.v3.min.js"></script>
<head>
<title>D3 Sparkline</title>
</head>
<style>
body {
font-family:"Lucida Grande","Droid Sans",Arial,Helvetica,sans-serif;
}
.legendwrap {
width: 300px;
}
.bld {
font-weight: bold;
}
.mine {
background-color: #9ACC73;
fill: #9ACC73;
}
.yours {
background-color: #4D7FBF;
fill: #4D7FBF;
}
.rsp {
stroke: #FF0000;
stroke-width: 0.5px;
}
.oversvg {
padding: 50px;
}
</style>
<body>
</body>
<script>
d3.json("data.json", function(error, json) {
var h = 75;
var t = json.edges.length;
var w = 300;
// dymanically calculate width, shrinks ticks to fit the size
var sw = Math.min(w/t, 25);
var svg = d3.select("body")
.append("svg:svg")
.attr("height", h)
.attr("width", w)
.attr("class", "oversvg");
var node = svg.selectAll("g.tick")
.data(json.edges)
.enter().append("svg:g")
.attr("class", "tick");
node.append("svg:rect")
.attr("class", function(d) {
var retval = '';
d['mine'] == 1 ? retval += "mine": retval += "yours";
d['resp'] == 1 ? d['mine'] == 0 ? retval += " rsp" : '' : '';
return retval;
})
.attr("x", function(d, i) {
return i * sw + 1;
})
.attr("y", function(d) {
return d['top']==1?0:h/2;
})
.attr("height", h/2-1)
.attr("width", function(d) {
return sw - 1.5;
});
node.append("svg:title")
.text(function (d) {
return d['name'];
});
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment